删除列表中反向重复项的 Pythonic 方法

2022-01-10 00:00:00 python python-2.7 duplicates

问题描述

我有一个配对列表:

[0, 1], [0, 4], [1, 0], [1, 4], [4, 0], [4, 1]

我想删除所有重复的地方

and I want to remove any duplicates where

[a,b] == [b,a]

所以我们最终只有

[0, 1], [0, 4], [1, 4]

我可以做一个内在的 &外部循环检查反向对并附加到列表中,如果不是这种情况,但我确信有一种更 Pythonic 的方式来实现相同的结果.

I can do an inner & outer loop checking for the reverse pair and append to a list if that's not the case, but I'm sure there's a more Pythonic way of achieving the same results.


解决方案

如果需要保留列表中元素的顺序的话,可以使用sorted 函数并使用 map 像这样:

If you need to preserve the order of the elements in the list then, you can use a the sorted function and set comprehension with map like this:

lst = [0, 1], [0, 4], [1, 0], [1, 4], [4, 0], [4, 1]
data = {tuple(item) for item in map(sorted, lst)}
# {(0, 1), (0, 4), (1, 4)}

或者干脆没有像这样的map:

or simply without map like this:

data = {tuple(sorted(item)) for item in lst}

另一种方法是使用 frozenset,如 here 所示,但请注意,这仅在以下情况下有效您的列表中有不同的元素.因为像 set 一样,frozenset 总是包含唯一值.因此,您最终会在子列表中获得唯一值(丢失数据),这可能不是您想要的.

Another way is to use a frozenset as shown here however note that this only work if you have distinct elements in your list. Because like set, frozenset always contains unique values. So you will end up with unique value in your sublist(lose data) which may not be what you want.

要输出一个列表,您总是可以使用 list(map(list, result)),其中 result 是一组元组,仅在 Python-3.0 或更高版本中.

To output a list, you can always use list(map(list, result)) where result is a set of tuple only in Python-3.0 or newer.

相关文章