Keep duplicates in a list in Python

▼魔方 西西 提交于 2019-12-01 01:04:45

问题


I know this is probably an easy answer but I can't figure it out. What is the best way in Python to keep the duplicates in a list:

x = [1,2,2,2,3,4,5,6,6,7]

The output should be:

[2,6]

I found this link: Find (and keep) duplicates of sublist in python, but I'm still relatively new to Python and I can't get it to work for a simple list.


回答1:


This is a short way to do it if the list is sorted already:

x = [1,2,2,2,3,4,5,6,6,7]

from itertools import groupby
print [key for key,group in groupby(x) if len(list(group)) > 1]



回答2:


I'd use a collections.Counter:

from collections import Counter
x = [1, 2, 2, 2, 3, 4, 5, 6, 6, 7]
counts = Counter(x)
output = [value for value, count in counts.items() if count > 1]

Here's another version which keeps the order of when the item was first duplicated that only assumes that the sequence passed in contains hashable items and it will work back to when set or yeild was introduced to the language (whenever that was).

def keep_dupes(iterable):
    seen = set()
    dupes = set()
    for x in iterable:
        if x in seen and x not in dupes:
            yield x
            dupes.add(x)
        else:
            seen.add(x)

print list(keep_dupes([1,2,2,2,3,4,5,6,6,7]))



回答3:


keepin' it simple:

array2 = []
aux = 0
aux2=0
for i in x:
    aux2 = i
    if(aux2==aux):
        array2.append(i)
    aux= i
list(set(array2))

That should work



来源:https://stackoverflow.com/questions/15812547/keep-duplicates-in-a-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!