【问题标题】:Split python string by predifned indices [duplicate]通过预定义索引拆分python字符串[重复]
【发布时间】:2017-12-19 15:50:18
【问题描述】:

我有一个字符串,我想在特定位置将其拆分为字符串列表。分割点存储在单独的分割列表中。例如:

test_string = "thequickbrownfoxjumpsoverthelazydog"
split_points = [0, 3, 8, 13, 16, 21, 25, 28, 32]

...应该返回:

>>> ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

到目前为止,我有这个作为解决方案,但它看起来非常复杂,因为任务如此简单:

split_points.append(len(test_string))
print [test_string[start_token:end_token] for start_token, end_token in [(split_points[i], split_points[i+1]) for i in xrange(len(split_points)-1)]]

有什么好的字符串函数可以完成这项工作,或者这是最简单的方法吗?

提前致谢!

【问题讨论】:

  • Python 没有out-of-the-box 在位置拆分功能,如果您要求内置函数

标签: python string split


【解决方案1】:

像这样?

>>> map(lambda x: test_string[slice(*x)], zip(split_points, split_points[1:]+[None]))
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

我们ziping split_points 带有一个移位的自我,以创建所有连续切片索引对的列表,例如[(0,3), (3,8), ...]。我们需要手动添加最后一个切片(32,None),因为zip 会在最短序列用完时终止。

然后我们 map 在该列表上添加一个简单的 lambda 切片器。请注意创建 slice 对象的 slice(*x),例如slice(0, 3, None),我们可以使用标准item getter(Python 2 中的__getslice__)对序列(字符串)进行切片。

更多的 Pythonic 实现可以使用列表解析而不是 map+lambda

>>> [test_string[i:j] for i,j in zip(split_points, split_points[1:] + [None])]
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

【讨论】:

  • 为什么是 lambda?您可以在列表理解中解压缩元组,然后执行 [test_string[i:j] for i,j in zip(split_points, split_points[1:] + [None])]
  • 你说得对,在考虑“功能性”时,我总是误入maplambda:-)
【解决方案2】:

这可能不那么复杂:

>> test_string = "thequickbrownfoxjumpsoverthelazydog"
>> split_points = [0, 3, 8, 13, 16, 21, 25, 28, 32]
>> split_points.append(len(test_string))
>> print([test_string[i: j] for i, j in zip(split_points, split_points[1:])])
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

【讨论】:

    【解决方案3】:

    初稿:

    for idx, i in enumerate(split_points):
        try:
            print(test_string[i:split_points[idx+1]])
        except IndexError:
            print(test_string[i:])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 2019-09-22
      • 1970-01-01
      相关资源
      最近更新 更多