问题描述
是否可以使用 python 获取列表中重复的值?
Is it possible to get which values are duplicates in a list using python?
我有一个项目列表:
mylist = [20, 30, 25, 20]
我知道删除重复项的最佳方法是 set(mylist)
,但是是否有可能知道哪些值被复制了?如您所见,在此列表中,重复项是第一个和最后一个值.[0, 3]
.
I know the best way of removing the duplicates is set(mylist)
, but is it possible to know what values are being duplicated? As you can see, in this list the duplicates are the first and last values. [0, 3]
.
是否有可能在 python 中得到这个结果或类似的结果?我试图避免做出一个大得离谱的 if elif
条件语句.
Is it possible to get this result or something similar in python? I'm trying to avoid making a ridiculously big if elif
conditional statement.
推荐答案
这些答案是 O(n),所以比使用 mylist.count()
多一点代码,但比 mylist.count()
效率更高code>mylist 变长了
These answers are O(n), so a little more code than using mylist.count()
but much more efficient as mylist
gets longer
如果您只想知道重复项,请使用 collections.Counter
If you just want to know the duplicates, use collections.Counter
from collections import Counter
mylist = [20, 30, 25, 20]
[k for k,v in Counter(mylist).items() if v>1]
如果您需要了解索引,
from collections import defaultdict
D = defaultdict(list)
for i,item in enumerate(mylist):
D[item].append(i)
D = {k:v for k,v in D.items() if len(v)>1}
这篇关于在 Python 中识别列表中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!