数字应用于字符串的序列生成

2024-03-28 18:43:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过序列生成器,比如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']

Tags: thetonamefromyoureadmoveif
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()
extra_lists = [read[start:end] for start,end in zip(a,b)]
print extra_lists

你的意思是:

>>> [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'

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

相关问题 更多 >