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

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

    this is the way I had to do it because I challenged myself not to use other methods:

    def dupList(oldlist):
        if type(oldlist)==type((2,2)):
            oldlist=[x for x in oldlist]
        newList=[]
        newList=newList+oldlist
        oldlist=oldlist
        forbidden=[]
        checkPoint=0
        for i in range(len(oldlist)):
            #print 'start i', i
            if i in forbidden:
                continue
            else:
                for j in range(len(oldlist)):
                    #print 'start j', j
                    if j in forbidden:
                        continue
                    else:
                        #print 'after Else'
                        if i!=j: 
                            #print 'i,j', i,j
                            #print oldlist
                            #print newList
                            if oldlist[j]==oldlist[i]:
                                #print 'oldlist[i],oldlist[j]', oldlist[i],oldlist[j]
                                forbidden.append(j)
                                #print 'forbidden', forbidden
                                del newList[j-checkPoint]
                                #print newList
                                checkPoint=checkPoint+1
        return newList
    

    so your sample works as:

    >>>a = [1,2,3,3,3,4,5,6,6,7]
    >>>dupList(a)
    [1, 2, 3, 4, 5, 6, 7]
    

提交回复
热议问题