使用大小列表拆分字符串的pythonic方法是什么?

时间:2017-02-08 17:40:49

标签: python string split substring

实现这个的pythonic方法是什么:

s = "thisismystring"
keys = [4, 2, 2, 6]
new = []
i = 0
for k in keys:
    new.append(s[i:i+k])
    i = i+k

这确实给了我['this', 'is', 'my', 'string'],但是我觉得这是一种更优雅的方式。建议?

4 个答案:

答案 0 :(得分:6)

您可以使用itertools.accumulate(),也许:

Border

您可以通过添加从0开始的另一个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 调用来内联start值:

accumulate()

此版本可以制作成列表理解:

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'] ,包含在pairwise() function from the itertools documentation中:

tee()

我在itertools.chain() call中输入前缀为0的起始位置,而不是创建一个带连接的新列表对象。

答案 1 :(得分:3)

我会使用enumerate来累积:

[s[sum(keys[:i]): sum(keys[:i]) + k] for i, k in enumerate(keys)]

用你的例子:

>>> s = "thisismystring"
>>> keys = [4, 2, 2, 6]
>>> new = [s[sum(keys[:i]): sum(keys[:i]) + k] for i, k in enumerate(keys)]
>>> new
['this', 'is', 'my', 'string']

答案 2 :(得分:3)

可以使用islice。可能效率不高,但可能至少有趣而且简单。

>>> from itertools import islice
>>> s = 'thisismystring'
>>> keys = [4, 2, 2, 6]

>>> it = iter(s)
>>> [''.join(islice(it, k)) for k in keys]
['this', 'is', 'my', 'string']

答案 3 :(得分:1)

仅仅因为我认为必须有办法在没有显式循环的情况下做到这一点:

import re

s = "thisismystring"

keys = [4, 2, 2, 6]

new = re.findall((r"(.{{{}}})" * len(keys)).format(*keys), s)[0]

print(new)

<强>输出

('this', 'is', 'my', 'string')