如何在python中按顺序从多个列表中删除重复记录

时间:2016-12-15 08:35:16

标签: python

我有三个列表,每个列表中有四个值,我必须从这三个列表中删除重复值

以下是三个清单

country_list = ['USA', 'India', 'China', 'India']
city_list = ['New York', 'New Delhi', 'Beijing', 'New Delhi']
event_list = ['First Event', 'Second Event', 'Third Event', 'Second Event']

正如它在所有三个列表"印度","新德里"和第二个事件"重复,意味着他们再次相互重复。我想删除这些重复值,并希望结果像

country_list = ['USA', 'India', 'China']
city_list = ['New York', 'New Delhi', 'Beijing']
event_list = ['First Event', 'Second Event', 'Third Event']

那么我怎么能得到这个结果呢?

3 个答案:

答案 0 :(得分:3)

一种简单的方法是执行以下操作:

country_list = list(set(country_list))
city_list = list(set(city_list))
event_list = list(set(event_list))

希望这有帮助。

答案 1 :(得分:1)

这样的东西
country_list = list(set(country_list))
city_list = list(set(city_list))
event_list = list(set(event_list))

应该这样做。这是因为set根据定义不能有重复项。将列表转换为集合时,将丢弃重复项。如果您希望数据再次以列表的形式存在,则需要将其转换回列表,如上所示。在大多数情况下,您可以像使用列表一样使用该集。

例如

for item in set(country_list):
    print item

因此可能不需要转换回列表。

答案 2 :(得分:0)

只需使用set()即可。 请看一下:Python Sets

而且:Sets

对于你的名单,你可以这样做:

>>> city_list = ['New York', 'New Delhi', 'Beijing', 'New Delhi']

>>> set(city_list)

set(['New Delhi', 'New York', 'Beijing'])

>>> list(set(city_list))

['New Delhi', 'New York', 'Beijing']