Remove duplicated lists in list of lists in Python

后端 未结 4 1841
忘了有多久
忘了有多久 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 13:11

    If you don't care about the order for lists and sublists (and all items in sublists are unique):

    result = set(map(frozenset, g))
    

    If a sublist may have duplicates e.g., [1, 2, 1, 3] then you could use tuple(sorted(sublist)) instead of frozenset(sublist) that removes duplicates from a sublist.

    If you want to preserve the order of sublists:

    def del_dups(seq, key=frozenset):
        seen = {}
        pos = 0
        for item in seq:
            if key(item) not in seen:
                seen[key(item)] = True
                seq[pos] = item
                pos += 1
        del seq[pos:]
    

    Example:

    del_dups(g, key=lambda x: tuple(sorted(x)))
    

    See In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique while preserving order?

提交回复
热议问题