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

前端 未结 30 2460
梦谈多话
梦谈多话 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条回答
  •  猫巷女王i
    2020-11-22 01:07

    the third example of the accepted answer give an erroneous answer and does not attempt to give duplicates. Here is the correct version :

    number_lst = [1, 1, 2, 3, 5, ...]
    
    seen_set = set()
    duplicate_set = set(x for x in number_lst if x in seen_set or seen_set.add(x))
    unique_set = seen_set - duplicate_set
    

提交回复
热议问题