按索引列表拆分字符串

2024-04-19 15:37:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用索引列表分割一个字符串,在这个列表中,分割的段从一个索引开始,在下一个索引之前结束。

示例:

s = 'long string that I want to split up'
indices = [0,5,12,17]
parts = [s[index:] for index in indices]
for part in parts:
    print part

返回:

long string that I want to split up
string that I want to split up
that I want to split up
I want to split up

我想得到:

long
string
that
I want to split up


Tags: to字符串in列表forstringindexthat
3条回答

如果不想对索引列表进行任何修改,可以编写生成器:

>>> def split_by_idx(S, list_of_indices):
...     left, right = 0, list_of_indices[0]
...     yield S[left:right]
...     left = right
...     for right in list_of_indices[1:]:
...         yield S[left:right]
...         left = right
...     yield S[left:]
... 
>>> 
>>> 
>>> s = 'long string that I want to split up'
>>> indices = [5,12,17]
>>> [i for i in split_by_idx(s, indices)]
['long ', 'string ', 'that ', 'I want to split up']

这里有一个简短的解决方案,其中大量使用了itertools module。函数tee用于对索引进行成对迭代。有关更多帮助,请参阅模块中的配方部分。

>>> from itertools import tee, izip_longest
>>> s = 'long string that I want to split up'
>>> indices = [0,5,12,17]
>>> start, end = tee(indices)
>>> next(end)
0
>>> [s[i:j] for i,j in izip_longest(start, end)]
['long ', 'string ', 'that ', 'I want to split up']

编辑:此版本不复制索引列表,因此应该更快。

s = 'long string that I want to split up'
indices = [0,5,12,17]
parts = [s[i:j] for i,j in zip(indices, indices[1:]+[None])]

回报

['long ', 'string ', 'that ', 'I want to split up']

您可以使用:

print '\n'.join(parts)

另一种可能(不复制indices)是:

s = 'long string that I want to split up'
indices = [0,5,12,17]
indices.append(None)
parts = [s[indices[i]:indices[i+1]] for i in xrange(len(indices)-1)]

相关问题 更多 >