Comparing over multiples keys is a common task in Python. To make it easier, multi_cmp creates a compound comparison function using the supplied keys and getter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def multi_cmp(keys, getter):
"""
keys - a list of keys which the getter will used compare with
getter - a getter, usually itemgetter or attrgetter from operator
This function builds a compound compare over multiple keys using the
supplied getter.
"""
def _cmp_with_keys(x,y):
for key in keys:
retVal = cmp(getter(key)(x), getter(key)(y))
if retVal:
return retVal
return 0
return _cmp_with_keys
|
The function allows you to turn something like: sorted(my_list, cmp=lambda x,y: cmp(x.attr1, y.attr1) or cmp(x.attr2, y.attr2)) into: sorted(my_list, cmp=multi_cmp(["attr1", "attr2"], operator.attrgetter))
Tags: shortcuts
use key= and multiple argument form of attrgetter. This is already supported using the key= argument to sorted() and the multiple argument form of attrgetter: