gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:49:36 26 4
gpt4 key购买 nike

我已经尝试过像 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']

最佳答案

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

关于python - 将数字应用于字符串的序列生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17240545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com