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

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

    Python 3.8 one-liner if you don't care to write your own algorithm or use libraries:

    l = [1,2,3,2,1,5,6,5,5,5]
    
    res = [(x, count) for x, g in groupby(sorted(l)) if (count := len(list(g))) > 1]
    
    print(res)
    

    Prints item and count:

    [(1, 2), (2, 2), (5, 4)]
    

    groupby takes a grouping function so you can define your groupings in different ways and return additional Tuple fields as needed.

    groupby is lazy so it shouldn't be too slow.

提交回复
热议问题