How to make deep comparisons of the equalities of two lists of tuples?

I want to compare two lists of tuples:

larry = [(1,'a'), (2, 'b')] moe = [(2, 'b'), (1, 'a')] 

so the order of the items in the list may vary. Are there library functions for this?

 >> deep_equals(larry, moe) True 
+6
source share
2 answers

If all you care about is the order of the items on the most remote list (this is what everything offers me except the word "deep", this in itself makes me doubt what you had in mind), and you know that there will be no duplicates, you can use set .

 >>> larry = [(1,'a'), (2, 'b')] >>> moe = [(2, 'b'), (1, 'a')] >>> set(larry) == set(moe) True 

If the case is as simple as these two sets, you can also use a dict , which will be {1: 'a', 2: 'b'} . This may or may not be a more convenient structure for you. In any case, comparing dict(larry) == dict(moe) will do what you want.

If you care about duplicates, it will take a little more work, taking copies of the lists and pulling out the elements one by one until it fails, or is empty.

+4
source

If I understand you, your tuples represent sets, and your lists are sets. The obvious thing to do is convert them to a set:

 def setterific(l): return frozenset(frozenset(p) for p in l) setterific(larry) == setterific(moe) 

This uses frozensets because python cannot have sets of sets (because sets are mutable); see How to create a collection of sets in Python? .

If you have only one set level, go to frozenset(larry) == frozenset(moe) .

+6
source

Source: https://habr.com/ru/post/908882/


All Articles