gpt4 book ai didi

python - 如何比较两个集合,其中每个元素都是列表?

转载 作者:太空宇宙 更新时间:2023-11-04 08:14:51 25 4
gpt4 key购买 nike

这是我的代码。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com