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

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

    Very simple and quick way of finding dupes with one iteration in Python is:

    testList = ['red', 'blue', 'red', 'green', 'blue', 'blue']
    
    testListDict = {}
    
    for item in testList:
      try:
        testListDict[item] += 1
      except:
        testListDict[item] = 1
    
    print testListDict
    

    Output will be as follows:

    >>> print testListDict
    {'blue': 3, 'green': 1, 'red': 2}
    

    This and more in my blog http://www.howtoprogramwithpython.com

提交回复
热议问题