开发者

remove duplicate list elements

I want to remove the duplicate elements in a list only when one element is repeated many times, like this:

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

but not when there are two or more different elements:

li = ['Human','Monkey','Human开发者_开发问答', 'Human']


You can do it easily with sets as below:

li = list(set(li))


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

Does that do what you want?

if so, then you can do it in place as well

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


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

it was do what you want?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜