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

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

    A bit late, but maybe helpful for some. For a largish list, I found this worked for me.

    l=[1,2,3,5,4,1,3,1]
    s=set(l)
    d=[]
    for x in l:
        if x in s:
            s.remove(x)
        else:
            d.append(x)
    d
    [1,3,1]
    

    Shows just and all duplicates and preserves order.

提交回复
热议问题