Algorithm - How to delete duplicate elements in a list efficiently?

前端 未结 16 2138
执念已碎
执念已碎 2020-12-01 04:21

There is a list L. It contains elements of arbitrary type each. How to delete all duplicate elements in such list efficiently? ORDE

16条回答
  •  -上瘾入骨i
    2020-12-01 04:25

    Generic solution close to the accepted answer

    k = ['apple', 'orange', 'orange', 'grapes', 'apple', 'apple', 'apple']
    m = []
    
    
    def remove_duplicates(k):
        for i in range(len(k)):
            for j in range(i, len(k)-1):
                if k[i] == k[j+1]:
                    m.append(j+1)
    
        l = list(dict.fromkeys(m))
        l.sort(reverse=True)
    
        for i in l:
            k.pop(i)
    
        return k
    
    
    print(remove_duplicates(k))
    

提交回复
热议问题