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

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

    How about simply loop through each element in the list by checking the number of occurrences, then adding them to a set which will then print the duplicates. Hope this helps someone out there.

    myList  = [2 ,4 , 6, 8, 4, 6, 12];
    newList = set()
    
    for i in myList:
        if myList.count(i) >= 2:
            newList.add(i)
    
    print(list(newList))
    ## [4 , 6]
    

提交回复
热议问题