这是我的代码。
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
关于python - 如何比较两个集合,其中每个元素都是列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16223176/