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

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

    We can use itertools.groupby in order to find all the items that have dups:

    from itertools import groupby
    
    myList  = [2, 4, 6, 8, 4, 6, 12]
    # when the list is sorted, groupby groups by consecutive elements which are similar
    for x, y in groupby(sorted(myList)):
        #  list(y) returns all the occurences of item x
        if len(list(y)) > 1:
            print x  
    

    The output will be:

    4
    6
    

提交回复
热议问题