如何比较两个集合,其中每个元素都列出?

时间:2013-04-25 19:29:03

标签: python list set

这是我的代码。

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'

那么,该怎么做?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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