Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform deep equality comparisons of two lists of tuples?

Tags:

python

I want to compare two lists of tuples:

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

such that the order of the items in the list may differ. Are there library functions to do this ?

>> deep_equals(larry, moe)
True
like image 356
canadadry Avatar asked Feb 20 '12 11:02

canadadry


1 Answers

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

def setterific(l):
    return frozenset(frozenset(p) for p in l)

setterific(larry) == setterific(moe)

This uses frozensets, because one cannot have sets of sets in python (because sets are mutable); see How can I create a Set of Sets in Python?.

If you only have one level of sets, go with frozenset(larry) == frozenset(moe).

like image 56
Marcin Avatar answered Sep 20 '22 02:09

Marcin