Removing duplicates from a list of lists

前端 未结 12 1436
萌比男神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:07

    Another probably more generic and simpler solution is to create a dictionary keyed by the string version of the objects and getting the values() at the end:

    >>> dict([(unicode(a),a) for a in [["A", "A"], ["A", "A"], ["A", "B"]]]).values()
    [['A', 'B'], ['A', 'A']]
    

    The catch is that this only works for objects whose string representation is a good-enough unique key (which is true for most native objects).

提交回复
热议问题