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

前端 未结 30 2494
梦谈多话
梦谈多话 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:09

    I guess the most effective way to find duplicates in a list is:

    from collections import Counter
    
    def duplicates(values):
        dups = Counter(values) - Counter(set(values))
        return list(dups.keys())
    
    print(duplicates([1,2,3,6,5,2]))
    

    It uses Counter once on all the elements, and then on all unique elements. Subtracting the first one with the second will leave out the duplicates only.

提交回复
热议问题