Skip to main content
 首页 » 编程设计

python之如何比较两个集合,其中每个元素都是列表

2025年05月04日43txw1958

这是我的代码。

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