簡體   English   中英

從2d列表中刪除重復項,無論順序如何

[英]remove duplicates from 2d lists regardless of order

我有一個二維清單

a = [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]

如何獲得結果:

result = [[1,2],[1,3],[2,3]]

無論內部列表的順序如何,都將刪除重復項。

嘗試使用一組來跟蹤您看到的列表:

from collections import Counter

a = [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 1]]

seen = set()
result = []
for lst in a:
    current = frozenset(Counter(lst).items())
    if current not in seen:
        result.append(lst)
        seen.add(current)

print(result)

哪個輸出:

[[1, 2], [1, 3], [2, 3], [1, 2, 1]]

注意:由於列表不具有哈希功能,因此您可以存儲Counter對象的凍結集,以檢測順序少的重復項。 這完全消除了排序的需要。

In [3]: b = []
In [4]: for aa in a:
...:     if not any([set(aa) == set(bb) for bb in b if len(aa) == len(bb)]):
...:         b.append(aa)
In [5]: b
Out[5]: [[1, 2], [1, 3], [2, 3]]

盡管我喜歡@RoadRunner的FrozenSet想法(集合很有用,並且它們使您能夠找到獨特的元素而無需重新發明輪子/試圖比開發Python的人更聰明),但是您也可以嘗試類似的方法只是嘗試刪除每個元素的反向子列表。 不利的一面是,如果您有一堆非重復項,那么它可能會過於昂貴:

a = [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]

result = a.copy()
for x in result:
  try:
    result.remove([x[-1::-1])
  except:
    pass

>>> [[1, 2], [1, 3], [2, 3]]

這應該適用於任意大小的子列表。

“設置”概念將在這里派上用場。 您擁有的列表(包含重復項)可以轉換為Set(永遠不包含重復項)。 在這里找到有關Set的更多信息: Set

范例:

l = ['foo', 'foo', 'bar', 'hello']

可以直接創建一個集合:

s = set(l)

現在,如果您檢查列表的內容

print(s)
>>> {'foo', 'bar', 'hello'}

Set將以這種方式與任何可迭代對象一起工作! 希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM