如何在列表中找到重复项并使用它们创建另一个列表? [英] How do I find the duplicates in a list and create another list with them?
问题描述
如何在Python列表中找到重复项并创建另一个重复项列表?该列表仅包含整数.
How can I find the duplicates in a Python list and create another list of the duplicates? The list only contains 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]
请注意,Counter
并不是特别有效(定时),并且在这里可能会过大. set
将表现更好.此代码按源顺序计算唯一元素的列表:
Note that Counter
is not particularly efficient (timings) and probably overkill here. set
will perform better. This code computes a list of unique elements in the source order:
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)]
我不建议使用后一种样式,因为not seen.add(x)
的作用不明显(set add()
方法始终返回None
,因此需要not
).
I don't recommend the latter style, because it is not obvious what not seen.add(x)
is doing (the set add()
method always returns None
, hence the need for not
).
要计算不包含库的重复元素的列表,请执行以下操作:
To compute the list of duplicated elements without libraries:
seen = {}
dupes = []
for x in a:
if x not in seen:
seen[x] = 1
else:
if seen[x] == 1:
dupes.append(x)
seen[x] += 1
如果列表元素不可散列,则不能使用集合/字典,而必须求助于二次时间解(将每个解比较).例如:
If list elements are not hashable, you cannot use sets/dicts and have to resort to a quadratic time solution (compare each with 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屋!