Python: Remove Sublists from List if Same Including/Not Including Order

做~自己de王妃 提交于 2019-12-12 12:27:36

问题


Is there a way to remove duplicate sublists from a list of lists, even if they are not the same ordering?

So could I do something like make:

x = [[1,2],[3,4],[5,6],[2,1],[7,8]]

into

x = [[1,2],[3,4],[5,6],[7,8]]

Is there an itertools function or something with a for loop?

Thanks!


回答1:


this will preserve the order of list and sublists, with possible duplicates in sublists:

y, s = [], set()
for t in x:
    w = tuple(sorted(t))
    if not w in s:
        y.append(t)
        s.add(w)

if

x = [[1,2],[3,4],[5,6],[2,1,1],[2,1],[7,8],[4,3],[1,2,1]]

then y will be:

[[1, 2], [3, 4], [5, 6], [2, 1, 1], [7, 8]]



回答2:


You can use frozenset:

>>> def remove_dups(L):
        return map(list, frozenset(map(frozenset, L)))

>>> x = [[1,2],[3,4],[5,6],[2,1],[7,8]]
>>> remove_dups(x)
[[5, 6], [1, 2], [8, 7], [3, 4]]
>>> 



回答3:


try this:

a=[[1,2],[3,4],[5,6],[2,1],[7,8]]
y=[]
for i in a:
        if sorted(i) not in y:
                y.append(i)
print y

output is

[[1, 2], [3, 4], [5, 6], [7, 8]]


来源:https://stackoverflow.com/questions/20462664/python-remove-sublists-from-list-if-same-including-not-including-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!