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

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

    Without converting to list and probably the simplest way would be something like below. This may be useful during a interview when they ask not to use sets

    a=[1,2,3,3,3]
    dup=[]
    for each in a:
      if each not in dup:
        dup.append(each)
    print(dup)
    

    ======= else to get 2 separate lists of unique values and duplicate values

    a=[1,2,3,3,3]
    uniques=[]
    dups=[]
    
    for each in a:
      if each not in uniques:
        uniques.append(each)
      else:
        dups.append(each)
    print("Unique values are below:")
    print(uniques)
    print("Duplicate values are below:")
    print(dups)
    

提交回复
热议问题