你可以使用itertools.accumulate(),也许:
from itertools import accumulate
s = "thisismystring"
keys = [4, 2, 2, 6]
new = []
start = 0
for end in accumulate(keys):
new.append(s[start:end])
start = end
您可以通过添加另一个从零开始的 accumulate() 调用来内联 start 值:
for start, end in zip(accumulate([0] + keys), accumulate(keys)):
new.append(s[start:end])
这个版本可以做成列表推导式:
[s[a:b] for a, b in zip(accumulate([0] + keys), accumulate(keys))]
后一版本的演示:
>>> from itertools import accumulate
>>> s = "thisismystring"
>>> keys = [4, 2, 2, 6]
>>> [s[a:b] for a, b in zip(accumulate([0] + keys), accumulate(keys))]
['this', 'is', 'my', 'string']
双重累加可以替换为tee(),包裹在pairwise() function from the itertools documentation中:
from itertools import accumulate, chain, tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
[s[a:b] for a, b in pairwise(accumulate(chain([0], keys)))]
我添加了一个itertools.chain() call 来作为起始位置 0 的前缀,而不是使用串联创建一个新的列表对象。