Removing duplicates from a list of lists

前端 未结 12 1499
萌比男神i
萌比男神i 2020-11-22 10:37

I have a list of lists in Python:

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]

And I want to remove duplicate elements from it. Was if it

12条回答
  •  广开言路
    2020-11-22 11:15

    Doing it manually, creating a new k list and adding entries not found so far:

    k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
    new_k = []
    for elem in k:
        if elem not in new_k:
            new_k.append(elem)
    k = new_k
    print k
    # prints [[1, 2], [4], [5, 6, 2], [3]]
    

    Simple to comprehend, and you preserve the order of the first occurrence of each element should that be useful, but I guess it's quadratic in complexity as you're searching the whole of new_k for each element.

提交回复
热议问题