Remove duplicated lists in list of lists in Python

后端 未结 4 1852
忘了有多久
忘了有多久 2021-01-13 12:10

I\'ve seen some questions here very related but their answer doesn\'t work for me. I have a list of lists where some sublists are repeated but their elements may be disorder

4条回答
  •  无人及你
    2021-01-13 12:54

    I would convert each element in the list to a frozenset (which is hashable), then create a set out of it to remove duplicates:

    >>> g = [[1, 2, 3], [3, 2, 1], [1, 3, 2], [9, 0, 1], [4, 3, 2]]
    >>> set(map(frozenset, g))
    set([frozenset([0, 9, 1]), frozenset([1, 2, 3]), frozenset([2, 3, 4])])
    

    If you need to convert the elements back to lists:

    >>> map(list, set(map(frozenset, g)))
    [[0, 9, 1], [1, 2, 3], [2, 3, 4]]
    

提交回复
热议问题