简体   繁体   English

如何删除嵌套列表中的重复项?

[英]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] . 由于[-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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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