使用Number应用于字符串的序列生成

时间:2013-06-21 16:56:30

标签: python string python-2.7

我尝试过像Lambda,List comprehension等序列生成器,但似乎我无法得到我真正想要的东西。我的最终目标是从 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 个答案:

答案 0 :(得分: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返回元组列表,其中每个元组包含传递给它的迭代中相同索引上的项:

>>> 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]

答案 1 :(得分:3)

你的意思是:

>>> [read[i:j] for i, j in zip(a,b)]
[['If', 'you', 'are', 'done', 'with', 'the', 'file,', 'move', 'to', 'the', 
'command',    'area'], ['from', 'the', 'file', 'name', 'in', 'the', 'RL',
'screen', 'and', 'type'], [], []]

>>> ' '.join[read[i:j] for i, j in zip(a,b)][0])
'If you are done with the file, move to the command area'

>>> ' '.join[read[i:j] for i, j in zip(a,b)][1])
'from the file name in the RL screen and type'

答案 2 :(得分: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

答案 3 :(得分:1)

你提到了一个lambda,所以:

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

好像你在两个列表中做切片索引,我可以建议一个字典或一个元组列表吗?

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。