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

Python 将数字应用于字符串的序列生成,python,string,python-2.7,Python,String,Python 2.7,我尝试过序列生成器,如Lambda、List-comprehension和其他,但似乎无法得到我真正想要的。我的最终目标是打印类似字符串[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.

我尝试过序列生成器,如Lambda、List-comprehension和其他,但似乎无法得到我真正想要的。我的最终目标是打印类似字符串[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']
使用
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
更新:创建
a
b

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

你提到了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。

您的意思是:

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


那么,问题是什么?如果我可以问的话,你在什么情况下发现了这样的问题?我如何创建列表a和b。在a和b的情况下,这些序列中的N+1数字是13。也就是b[0]=a[0]+12
>>> ' '.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'