我想用索引列表分割一个字符串,在这个列表中,分割的段从一个索引开始,在下一个索引之前结束。
示例:
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
如果不想对索引列表进行任何修改,可以编写生成器:
这里有一个简短的解决方案,其中大量使用了itertools module。函数
tee
用于对索引进行成对迭代。有关更多帮助,请参阅模块中的配方部分。编辑:此版本不复制索引列表,因此应该更快。
回报
您可以使用:
另一种可能(不复制
indices
)是:相关问题 更多 >
编程相关推荐