简体   繁体   中英

How to remove duplicates in nested lists?

I want to remove both duplicates and permutations from my nested list.

Input:

[[-1, 0, 1], [-1, 1, 0], [-1, 2, -1], [-1, 2, -1], [-1, -1, 2]]

Expected Output:

[[-1, 0, 1], [-1, 2, -1]]

I tried using a list comprehension but I end up with the output as

[[-1, 1, 0], [-1, 2, -1], [-1, 0, 1], [-1, -1, 2]]

Here is what I attempted.

a = [[-1, 0, 1], [-1, 1, 0], [-1, 2, -1], [-1, 2, -1], [-1, -1, 2]]
b_set = set(tuple(x) for x in a)
b = [ list(x) for x in b_set ]
print(b)

The result is expected because [-1, 0, 1] != [-1, 1, 0] . You can sort the inner tuples if you want to make sure that they are considered equal:

b_set = set(tuple(sorted(x)) for x in a)

或与map

b_set = set(map(lambda x: tuple(sorted(x)),a))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM