def greatest(values):
value_generator = (v for k,v in values)
max_value = max(value_generator)
return (k for k,v in values if v == max_value)
sample_data = ( ('id1', 3), ('id2', 5), ('id3', 5) )
items = list( greatest(sample_data) ) # Should produce ['id2', 'id3']
MapReduce anyone?
In fact, according to my tests, your version of
greatestis faster — by a bit, anyway:Of course, if you don’t like assigning your generator to a name, you can just pass the generator to max directly — way more readable than
max(values, key=itemgetter(1))[1], IMHO:Python allows you to omit the outer parens when doing things like this:
But for reasons I don’t understand, doing it that way is slightly slower:
These are true micro-optimizations, unlikely to matter much. But I think that readability favors
max(v for k, v in values)ormax((v for k, v in values))overmax(values, key=itemgetter(1))[1].