問題描述
我有一個配對列表:
[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.
這篇關于刪除列表中反向重復項的 Pythonic 方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!