Python: Remove Duplicate Items from Nested list

纵然是瞬间 提交于 2019-11-27 15:20:51

If the Order Matters you can always use OrderedDict

>>> unq_lst = OrderedDict()
>>> for e in lst:
    unq_lst.setdefault(frozenset(e),[]).append(e)


>>> map(list, unq_lst.keys())
[[1, 2], [4, 5], [3, 4]]
lst=[[1,2],[4,5],[3,4],[4,3],[2,1],[1,2]]
fset = set(frozenset(x) for x in lst)
lst = [list(x) for x in fset]

This won't preserve order from your original list, nor will it preserve order of your sublists.

>>> lst=[[1,2],[4,5],[3,4],[4,3],[2,1],[1,2]]
>>> fset = set(frozenset(x) for x in lst)
>>> lst = [list(x) for x in fset]
>>> lst
[[1, 2], [3, 4], [4, 5]]

If order is not important:

def rem_dup(l: List[List[Any]]) -> List[List[Any]]:
    tuples = map(lambda t: tuple(sorted(t)), l)
    return [list(t) for t in set(tuples)]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!