如何在列表中找到重复项并用它们创建另一个列表? [英] How do I find the duplicates in a list and create another list with them?

查看:25
本文介绍了如何在列表中找到重复项并用它们创建另一个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 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 in seen or 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆