繁体   English   中英

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

[英]How to compare two sets, where each element of them is list?

这是我的代码。

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

当列表的元素不可散列时(例如列表), 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM