How do I find the duplicates in a list and create another list with them?

前端 未结 30 1658
梦谈多话
梦谈多话 2020-11-22 00:56

How can I find the duplicates in a Python list and create another list of the duplicates? The list only contains integers.

30条回答
  •  别那么骄傲
    2020-11-22 01:20

    collections.Counter is new in python 2.7:

    
    Python 2.5.4 (r254:67916, May 31 2010, 15:03:39) 
    [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
    a = [1,2,3,2,1,5,6,5,5,5]
    import collections
    print [x for x, y in collections.Counter(a).items() if y > 1]
    Type "help", "copyright", "credits" or "license" for more information.
      File "", line 1, in 
    AttributeError: 'module' object has no attribute 'Counter'
    >>> 
    

    In an earlier version you can use a conventional dict instead:

    a = [1,2,3,2,1,5,6,5,5,5]
    d = {}
    for elem in a:
        if elem in d:
            d[elem] += 1
        else:
            d[elem] = 1
    
    print [x for x, y in d.items() if y > 1]
    

提交回复
热议问题