gpt4 book ai didi

python - 在不更改列表的原始顺序的情况下删除作为列表中其他字符串的子字符串的字符串?

转载 作者:行者123 更新时间:2023-11-28 22:33:25 25 4
gpt4 key购买 nike

我有一个列表。

the_list = ['Donald Trump has', 'Donald Trump has small fingers', 'What is going on?']

我想从 the_list 中删除“Donald Trump has”,因为它是其他列表元素的子字符串。

这是一个重要的部分。我想在不破坏原始列表顺序的情况下执行此操作。

我的函数(如下)扭曲了原始列表的顺序。因为它首先按长度对列表项进行排序。

def substr_sieve(list_of_strings):  
dups_removed = list_of_strings[:]
for i in xrange(len(list_of_strings)):
list_of_strings.sort(key = lambda s: len(s))
j=0
j=i+1
while j <= len(list_of_strings)-1:
if list_of_strings[i] in list_of_strings[j]:
try:
dups_removed.remove(list_of_strings[i])
except:
pass
j+=1
return dups_removed

最佳答案

一个简单的解决方案。

但首先,让我们在最后添加“Donald Trump”、“Donald”“Trump” 以使其更好测试用例。

>>> forbidden_text = "\nX08y6\n" # choose a text that will hardly appear in any sensible string
>>> the_list = ['Donald Trump has', 'Donald Trump has small fingers', 'What is going on?',
'Donald Trump', 'Donald', 'Trump']
>>> new_list = [item for item in the_list if forbidden_text.join(the_list).count(item) == 1]
>>> new_list
['Donald Trump has small fingers', 'What is going on?']

逻辑:

  1. 连接所有列表元素以形成一个字符串。forbidden_​​text.join(the_list)
  2. 搜索列表中的项目是否只出现过一次。如果它出现不止一次,它就是一个子字符串。count(item) == 1

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.


forbidden_​​text 用于代替 ""(空白字符串),以处理此类情况:

>>> the_list = ['DonaldTrump', 'Donald', 'Trump']


正如 Nishant 所指出的,上面的代码对于 the_list = ['Donald', 'Donald'] 是失败的

使用 set(the_list) 而不是 the_list 解决了这个问题。
>>> new_list = [item for the_list if forbidden_​​text.join(set(the_list)).count(item) == 1]

关于python - 在不更改列表的原始顺序的情况下删除作为列表中其他字符串的子字符串的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39930434/

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