簡體   English   中英

如何比較兩個集合,其中每個元素都是列表?

[英]How to compare two sets, where each element of them is list?

這是我的代碼。

a = [
        ['StarList', 'StarId38', 'ShipList']
    ]
b = [
        ['StarList', 'StarId3', 'ShipList'],
        ['StarList', 'StarId4', 'ShipList']
    ]
assert set(a) == set(b) # False

a = [
        ['StarList', 'StarId4', 'ShipList'],
        ['StarList', 'StarId3', 'ShipList']
    ]
assert set(a) == set(b) # True

它不起作用:

Traceback (most recent call last):
    File "compare.py", line 8, in <module>
        assert set(a) == set(b) # False
TypeError: unhashable type: 'list'

好吧,該怎么做呢?

比較之前,將內部列表轉換為元組或其他某種可哈希類型。

In [52]: a = [                               
        ['StarList', 'StarId38', 'ShipList']
    ]

In [53]: b = [                               
        ['StarList', 'StarId3', 'ShipList'],
        ['StarList', 'StarId4', 'ShipList']
    ]

In [54]: set(map(tuple, a)) == set(map(tuple, b))
Out[54]: False

In [55]: a = [
   ....:         ['StarList', 'StarId4', 'ShipList'],
   ....:         ['StarList', 'StarId3', 'ShipList']
   ....:     ]

In [56]: set(map(tuple,a))==set(map(tuple,b))
Out[56]: True

當列表的元素不可散列時(例如列表), set()不起作用。 因此,首先您應該考慮是否確實必須使用set 在這種情況下,刪除重復項的替代方法是itertools.groupby

import itertools
unique_a = [k for k,_ in itertools.groupby(a)]
unique_b = [k for k,_ in itertools.groupby(b)]
unique_a.sort()
unique_b.sort()

並嘗試(針對第二種情況):

>>> unique_a == unique_b
True

暫無
暫無

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

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