How to print only the duplicate elements in python

2020-02-13 05:53发布

Is there any inbuilt way to print duplicate elements present in a python list.

I can write program for the same.

All I'm searching for is if there is any inbuilt method or something for the same.

For Ex:

For input [4,3,2,4,5,6,4,7,6,8]

I need op 4,6

4条回答
狗以群分
2楼-- · 2020-02-13 06:27

Possibly related duplicate question: How do I find the duplicates in a list and create another list with them?

Simple Answer:

>>> l = [1,2,3,4,4,5,5,6,1]
>>> set([x for x in l if l.count(x) > 1])
set([1, 4, 5])
查看更多
看我几分像从前
3楼-- · 2020-02-13 06:28

There is the Counter class from collections that does the trick

from collections import Counter


lst = [4,3,2,4,5,6,4,7,6,8]
d =  Counter(lst)  # -> Counter({4: 3, 6: 2, 3: 1, 2: 1, 5: 1, 7: 1, 8: 1})
res = [k for k, v in d.items() if v > 1]
print(res)
# [4, 6]
查看更多
Anthone
4楼-- · 2020-02-13 06:30

with simple built-in function you can do :

>>> a=[4,3,2,4,5,6,4,7,6,8]
>>> b=[a[i] for i in range(len(a)) if a[i] in a[:i]][1:]
>>> b
[4, 6]
查看更多
够拽才男人
5楼-- · 2020-02-13 06:45

Here is a simple demo

    x = [1,2,3,5,3,2]
    y = []
    for a in x:
        if not a in y:
            y.append(a)
    print(a)

So here is how it works.Iterate over every items in x.If the current iteration item doesn't exist in y append it

查看更多
登录 后发表回答