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

2 回答 2

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
于 2013-04-25T19:31:53.527 回答
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
于 2013-04-25T19:30:54.103 回答