【问题标题】:Splitting a string by list of indices按索引列表拆分字符串
【发布时间】:2012-06-06 18:19:37
【问题描述】:

我想通过索引列表拆分字符串,其中拆分段以一个索引开始并在下一个索引之前结束。

示例:

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

这将返回:

我要拆分的长字符串
我要拆分的字符串
我想分手
我想分手

我想得到:


字符串

我想分手

【问题讨论】:

    标签: python string split indices


    【解决方案1】:
    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)]
    

    【讨论】:

    • 另一种方式是,[s[i:j] for i,j in izip_longest(indices,indices[1:])],但我更喜欢你的方式!
    • 这会使用indices[1:] 复制索引列表,并通过zip 函数创建一个双倍大小的新列表 -> 性能不佳和内存消耗。
    • @ms4py 这很好,在这种情况下性能不是问题,这是一个非常易读的解决方案。如果性能是一个问题,可以使用我的建议。
    • eumiro-谢谢,这很好用。你能解释一下 +[None] 部分是如何工作的吗?
    • @ms4py - 好的,有一个更新版本,没有复制列表,也没有 zip。尽管您的 itertools 版本可能性能更高。
    【解决方案2】:

    这是一个使用大量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']
    

    编辑:这是一个不复制索引列表的版本,所以应该更快。

    【讨论】:

    • 感谢您的 alt 方法 - 有时必须查看 itertools
    • 简洁的方法,学到了新的东西。有没有一种简单的方法可以消除表达式中前 3 个字符串末尾的多余空格?我尝试了s[i:j].strip(),但这根本不起作用(不知道为什么不)
    • 如果你要使用它,你也可以直接使用 itertools 文档中的 pairwise 函数。同样使用next(end) 优于end.next() 以实现python 3 兼容性。
    【解决方案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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2011-06-09
      • 2022-01-22
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      相关资源
      最近更新 更多