如何从列表中删除重复的字符串(Python3)



我已经从一段文本中提取了一个单词列表,但我想从该列表中删除重复的单词。我该怎么做呢?

我输出:

["出现","但是","它","朱丽叶","谁","已经","one_answers","one_answers","one_answers","休息","东","嫉妒",‘公平’,‘悲伤’,‘是’,‘是’,‘是’,‘杀’,‘光’,‘月亮’,‘白’,‘病’,‘软’,‘太阳’,‘太阳’,‘的’,‘的’,‘的’,‘穿越’,‘什么’,‘窗口’,‘与’,‘那边’]

所需输出:

["出现","但是","它","朱丽叶","谁","已经",’和‘,‘休息’,‘东’,‘嫉妒’,‘公平’,‘悲伤’,‘是’,‘杀’,‘光’,‘月亮’,‘白’,‘病’,‘软’,‘太阳’,‘的’,‘穿越’,‘什么’,‘窗口’,‘与’,‘那边’]

一种方法是通过提取每个列表的相同键来删除列表重复项,一个名为"fromkeys"的dict对象函数,该函数删除重复元素:

test_list = ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'is', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'sun', 'the', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder']
test_list = list(dict.fromkeys(test_list))
print(test_list)

的另一种方法是,你可以在一个for循环迭代列表:

res = list()
for item in test_list:
if item not in res:
res.append(item)

最后一种方法的更简洁的版本如下:

res = list()
[res.append(item) for item in test_list if item not in res]

整个输出:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

Jussi的答案也是正确的,set也删除了列表重复项:

test_list = list(set(test_list))

最新更新