我有以下列表: Liste = ['hello','hello word','word','red','red apple','apple','king'] 我想删除包含“hello”和“word”,“red”和“apple”之类的重复单词 所以ResultsList将是这样的:['hello word','red apple','king']我尝试了一些方法,但对我不起作用! 那么任何人都可以帮助解决我的问题的简单方法吗?
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()将起作用。