Identify duplicate values in a list in Python

前端 未结 12 1890
渐次进展
渐次进展 2020-11-29 06:31

Is it possible to get which values are duplicates in a list using python?

I have a list of items:

    mylist = [20, 30, 25, 20]

I k

12条回答
  •  渐次进展
    2020-11-29 07:08

    These answers are O(n), so a little more code than using mylist.count() but much more efficient as mylist gets longer

    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]
    

    If you need to know the indices,

    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}
    

提交回复
热议问题