简体   繁体   English

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

[英]What's the pythonic way to split a string using a list of sizes?

What's the pythonic way to implement this: 实现这个的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 does give me ['this', 'is', 'my', 'string'] as I need but I fell there's a more elegant way to do it. 这确实给了我['this', 'is', 'my', 'string'] ,但是我觉得这是一种更优雅的方式。 Suggestions? 建议?

You could use itertools.accumulate() , perhaps: 您可以使用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

You could inline the start values by adding another accumulate() call starting at zero: 你可以内联start通过增加另一个值accumulate()从零开始电话:

for start, end in zip(accumulate([0] + keys), accumulate(keys)):
    new.append(s[start:end])

This version can be made into a list comprehension: 这个版本可以制成列表理解:

[s[a:b] for a, b in zip(accumulate([0] + keys), accumulate(keys))]

Demo of the latter version: 演示后者版本:

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

The double accumulate could be replaced with a tee() , wrapped in the pairwise() function from the itertools documentation : double accumulate可以替换为tee() ,包含在itertools文档中的itertools pairwise()函数中

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

I threw in an itertools.chain() call to prefix that 0 starting position, rather than create a new list object with concatenation. 我在一个itertools.chain()调用中输入前缀为0的起始位置,而不是创建一个带有连接的新列表对象。

I would use enumerate for that, with accumulating: 我会使用enumerate ,累积:

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

With your example: 用你的例子:

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

Could use islice . 可以使用islice Probably not efficient, but maybe at least interesting and simple. 可能效率不高,但可能至少有趣而且简单。

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

Just because I believe there have to be ways to do this without explicit loops: 仅仅因为我认为必须有办法在没有显式循环的情况下做到这一点:

import re

s = "thisismystring"

keys = [4, 2, 2, 6]

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

print(new)

OUTPUT OUTPUT

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM