gpt4 book ai didi

python - 删除列表python中以特定事物开头的后面的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 12:57:48 24 4
gpt4 key购买 nike

我有一个这样的列表:

['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 的评论,列表已排序)

最佳答案

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

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]

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

关于python - 删除列表python中以特定事物开头的后面的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34246191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com