2013-04-25 60 views
1

這是我的代碼。如何比較兩個集合,其中的每個元素是列表?

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' 

好了,該怎麼辦呢?

回答

4

轉換內部列表來元組或比較之前的一些其他類型的哈希的。

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 
+0

這會創建中間列表,集合和元組,這可能會非常好。如果更改子列表的順序是可以接受的,請對每個子列表進行排序然後進行比較。 – 2013-04-25 19:47:13

2

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 
+0

-1。 'aList.sort()'返回'None',所以'unique_a.sort()== unique_b.sort()'將永遠是'True',因爲'None == None'。嘗試例如'[1] .sort()== [3,2] .sort()'。 – 2013-04-25 19:43:29

+0

Steven Rumbalski:你說得對,謝謝你指出錯誤。我編輯了答案,提前進行排序。 – tiago 2013-04-25 19:48:03

+0

我寧願做'排序(unique_a)==排序(unique_b)' – jamylak 2013-04-26 00:58:59

相關問題