How do you remove duplicates in a 2d list with the same values but different order

35 Views Asked by At

I have a list which contains lists. I am trying to remove any duplicates of lists which may share the same items within the list but in a different order.

for example if I have this

nestedlist=[[1,2,3,4],[4,3,2,1],[1,5,8,7]]

I would like a function that returns something like:

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

There are 2 best solutions below

2
Bhargav - Retarded Skills On BEST ANSWER

Sort the list after acessing sub list and compare accordingly.

new=[]
nestedlist=[[1,2,3,4],[4,3,2,1],[1,5,8,7]]
for i in nestedlist:
    if sorted(i) not in new:
        new.append(i)

print(new)

Gives #

[[1, 2, 3, 4], [1, 5, 8, 7]]         
0
pho On

Make a set of sets out of the list of lists. Then convert it back to a list of lists:

sos = {frozenset(l) for l in nestedlist}
unique_nested = [list(s) for s in sos]

We need to use frozenset instead of set because sets are mutable therefore not hashable