简体   繁体   中英

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). So first you should considerer if you really must use set . An alternative to remove duplicates in this case is 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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