删除重复的列表元素

时间:2010-09-29 22:04:00

标签: python

我只想在一个元素重复多次时删除列表中的重复元素,如下所示:

li = ['Human','Human','Human'] => li = ['Human']

但不是在有两个或更多不同元素时:

li = ['Human','Monkey','Human', 'Human']

非常感谢提前。

3 个答案:

答案 0 :(得分:3)

def clean(lst):
    if lst.count(lst[0]) == len(lst):
        return [lst[0]]
    else:
        return lst

这样做你想要的吗?

如果是这样,那么你也可以在适当的地方做到这一点

def clean_in_place(lst):
    if lst.count(lst[0]) == len(lst):
        lst[:] = [lst[0]]

答案 1 :(得分:3)

您可以使用以下设置轻松完成:

li = list(set(li))

答案 2 :(得分:2)

lst = ['Human','Human','Human'] => lst = ['Human']
lst = ['Human','Monkey','Human', 'Human'] => lst = ['Human','Monkey','Human', 'Human']

它是你想做的吗?

if lst.count(lst[0])==len(lst):
   lst=list(set(lst))
   print lst 
else:
   print lst 
相关问题