【问题标题】:remove later strings starting with a certain thing in a list python删除列表python中以特定事物开头的后续字符串
【发布时间】:2015-12-12 23:24:25
【问题描述】:

我有一个这样的列表:

['a b d', 'a b e', 'c d j', 'w x y', 'w x z', 'w x k']

我想删除以相同 4 个字符开头的字符串之后出现的所有字符串。例如,'a b e' 将被删除,因为 'a b d' 出现在它之前。

新列表应如下所示:

['a b d', 'c d j', 'w x y']

我该怎么做?

(注意:根据@Martijn Pieters 的评论,列表已排序)

【问题讨论】:

  • 那么['w x y', 'a b d', 'a b e', 'c d j', 'w x z', 'w x k'] 应该发生什么,其中'w x ' 是更晚出现的元素的前缀?输出是否仍为['w x y', 'a b d', 'c d j']
  • @Martijn Pieters - 列表已排序,所以这无关紧要
  • 四个字符在哪里?
  • @PadraicCunningham:包括空格,第一个字符串以'a b '开头。
  • @MartijnPieters,是的,明白了

标签: python string list startswith


【解决方案1】:

使用生成器函数来记住开始:

def remove_starts(lst):
    seen = []
    for elem in lst:
        if elem.startswith(tuple(seen)):
            continue
        yield elem
        seen.append(elem[:4])

因此,该函数会跳过以 seen 中的一个字符串开头的任何内容,将其允许的任何内容的前 4 个字符添加到该集合中。

演示:

>>> lst = ['a b d', 'a b e', 'c d j', 'w x y', 'w x z', 'w x k']
>>> def remove_starts(lst):
...     seen = []
...     for elem in lst:
...         if elem.startswith(tuple(seen)):
...             continue
...         yield elem
...         seen.append(elem[:4])
...
>>> list(remove_starts(lst))
['a b d', 'c d j', 'w x y']

如果您的输入已排序,则可以简化为:

def remove_starts(lst):
    seen = ()
    for elem in lst:
        if elem.startswith(seen):
            continue
        yield elem
        seen = elem[:4]

这通过限制为最后一个来节省前缀测试。

【讨论】:

  • 你为什么要使用一套?
  • @PadraicCunningham:hrm,你是对的,没有重复的机会。它必须是一个可变结构,但str.startswith() 只接受一个元组(或字符串)。
  • 难道不是集合实际上是存储集合中前四个字符并且仅在四个字符不在集合中时才产生的最佳方法吗?
  • @PadraicCunningham:我不知道;前缀测试非常快,但是从列表到元组的转换每次都会受到影响。我们可以计时,但我现在没时间了。
  • 我想这也归结为切片大小、字符串数量和具有唯一前缀的字符串。晚上也要签收,这样可能是另一天的工作
【解决方案2】:

您也可以使用OrderedDict,键可以是前四个字符,值是包含这四个字符的第一个字符串:

lst = ['a b d', 'a b e', 'c d j', 'w x y', 'w x z', 'w x k']

from collections import OrderedDict

print(list(OrderedDict((s[:4], s) for s in lst).values()))
['a b e', 'c d j', 'w x k']

【讨论】:

  • @BhargavRao,您本可以在编辑中使用这种花哨的拼写;)
  • 大声笑,我下次会这样做:D
猜你喜欢
  • 1970-01-01
  • 2015-03-02
  • 2018-12-22
  • 2022-11-28
  • 1970-01-01
  • 2014-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多