[英]How to compare two sets, where each element of them is list?
Here's my code. 这是我的代码。
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
It doesn't work: 它不起作用:
Traceback (most recent call last):
File "compare.py", line 8, in <module>
assert set(a) == set(b) # False
TypeError: unhashable type: 'list'
Well, how to do it? 好吧,该怎么做呢?
Convert the inner lists to tuple or some other hashable type before comparing. 比较之前,将内部列表转换为元组或其他某种可哈希类型。
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
set()
does not work when the elements of a list are unhashable (eg are a list). 当列表的元素不可散列时(例如列表),
set()
不起作用。 So first you should considerer if you really must use set
. 因此,首先您应该考虑是否确实必须使用
set
。 An alternative to remove duplicates in this case is itertools.groupby
: 在这种情况下,删除重复项的替代方法是
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()
And try (for your second case): 并尝试(针对第二种情况):
>>> unique_a == unique_b
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.