2

ラムダ、リスト内包表記などのシーケンス ジェネレーターを試しましたが、本当に必要なものを取得できないようです。私の最終的な目標は、 string[1:3]のような文字列から一連の単語を出力することです。

私が探しているもの:

a = [0,13,26,39]
b = [12,25,38,51]

str = 'If you are done with the file, move to the command area across from the file name in the RL screen and type'

read = str.split()

read[0:12]
['If', 'you', 'are', 'done', 'with', 'the', 'file,', 'move', 'to', 'the', 'command', 'area']
read[13:25]
['from', 'the', 'file', 'name', 'in', 'the', 'RL', 'screen', 'and', 'type']
4

4 に答える 4

5

使用zip:

>>> a = [0,13,26,39]
>>> b = [12,25,38,51]
>>> strs = 'If you are done with the file, move to the command area across from the file name in the RL screen and type'
>>> spl = strs.split()
>>> for x,y in zip(a,b):
...     print spl[x:y]
...     
['If', 'you', 'are', 'done', 'with', 'the', 'file,', 'move', 'to', 'the', 'command', 'area']
['from', 'the', 'file', 'name', 'in', 'the', 'RL', 'screen', 'and', 'type']
[]
[]

zipタプルのリストを返します。各タプルには、渡された iterables からの同じインデックスの項目が含まれます。

>>> zip(a,b)
[(0, 12), (13, 25), (26, 38), (39, 51)]

itertools.izipイテレータを返すため、メモリ効率の高いソリューションが必要な場合に使用します。

str.joinそのスライスされたリストから文字列を作成する場合に使用できます。

for x,y in zip(a,b):
    print " ".join(spl[x:y])
...     
If you are done with the file, move to the command area
from the file name in the RL screen and type

更新:作成ab:

>>> n = 5
>>> a = range(0, 13*n, 13)
>>> b = [ x + 12 for x in a]
>>> a
[0, 13, 26, 39, 52]
>>> b
[12, 25, 38, 51, 64]
于 2013-06-21T16:59:41.287 に答える
2
a = [0,13,26,39]
b = [12,25,38,51]
str = 'If you are done with the file, move to the command area across from the file name  in the RL screen and type'

read = str.split()
extra_lists = [read[start:end] for start,end in zip(a,b)]
print extra_lists
于 2013-06-21T17:01:24.093 に答える
1

あなたはラムダについて言及したので:

 f = lambda s, i, j: s.split()[i:j]
 >>> f("hello world how are you",0,2)
 ['hello', 'world']

2 つのリストでスライス インデックスを作成しているようですが、辞書またはタプルのリストを提案できますか?

str = 'If you are done with the file, move to the command area across from the file name in the RL screen and type'
slices = [(0, 13), (12, 25)]
dslices = {0:13, 12:25}
for pair in slices:
    print f(str, pair[0], pair[1])
for key in dslices:
    print f(str, key, dislikes[key])

データをより適切にフォーマットするオプションがある場合、私は zip を使用するのが好きではありません。

于 2013-06-21T17:00:33.760 に答える