I have the following list:
Liste=['hello','hello word','word','red','red apple','apple','king']
and I want to remove the duplicate words that include in other words like 'hello' and 'word','red', and 'apple'
so the ResultsList will be like this:['hello word', 'red apple','king']
i tried a few methods but didn't work for me!
So anyone can help with a simple solution to my problem?
答案 0 :(得分:0)
myList = ['hello','hello word','word','red','red apple','apple','king']
newList = []
for item in myList:
unique = True
current = myList.pop()
for string in myList:
if current in string:
unique = False
if unique:
newList.append(current)
myList.insert(0, current)
print(newList)
遍历列表,每次迭代都会弹出列表中的最后一个元素。此后,循环遍历其余元素,并评估我们弹出的字符串是否为其他任何剩余字符串的子字符串。
如果没有,我们认为我们弹出的字符串是唯一的,我们可以将其附加到一个空列表中。在每次循环迭代的末尾,插入我们弹出到原始列表开头的字符串。
如果您要删除完全重复的内容而不是子字符串,则set()将起作用。