在列表中查找并列出重复项? [英] Find and list duplicates in a list?
本文介绍了在列表中查找并列出重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Python列表中找到重复项并创建另一个重复列表?列表只是整数。
How can I find the duplicates in a Python list and create another list of the duplicates? The list is just integers.
推荐答案
要删除重复使用 set(a)
,打印重复的东西,如
To remove duplicates use set(a)
, to print duplicates - something like
a = [1,2,3,2,1,5,6,5,5,5]
import collections
print [item for item, count in collections.Counter(a).items() if count > 1]
## [1, 2, 5]
请注意计数器
不是特别有效(计时),可能在这里过度, set
将表现更好:
Note that Counter
is not particularly efficient (timings) and probably an overkill here, set
will perform better:
seen = set()
uniq = []
for x in a:
if x not in seen:
uniq.append(x)
seen.add(x)
或更简洁:
seen = set()
uniq = [x for x in a if x not in seen and not seen.add(x)]
尽管如此,我不推荐使用后一种风格。
I don't recommend the latter style though.
如果列表元素不可哈希,则不能使用set /例如:
If list elements are not hashable, you cannot use set/dicts and have to resort to a quadratic time solution (compare each which each), for example:
a = [ [1], [2], [3], [1], [5], [3] ]
no_dupes = [x for n, x in enumerate(a) if x not in a[:n]]
print no_dupes # [[1], [2], [3], [5]]
dupes = [x for n, x in enumerate(a) if x in a[:n]]
print dupes # [[1], [3]]
这篇关于在列表中查找并列出重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文