views:

188

answers:

3

Is there a better way of doing this? I don't really need the list to be sorted, just scanning through to get the item with the greatest specified attribute. I care most about readability but sorting a whole list to get one item seems a bit wasteful.

>>> import operator
>>> 
>>> a_list = [('Tom', 23), ('Dick', 45), ('Harry', 33)]
>>> sorted(a_list, key=operator.itemgetter(1), reverse=True)[0]
('Dick', 45)

I could do it quite verbosely...

>>> age = 0
>>> oldest = None
>>> for person in a_list:
...     if person[1] > age:
...             age = person[1]
...             oldest = person
... 
>>> oldest
('Dick', 45)
+26  A: 

max(a_list, key=operator.itemgetter(1))

fengb
Nice, didn't know that max had an optional key argument!
Noah
Ah, brilliant! Good python makes me happy.
StephenPaulger
+5  A: 

You could use the max function.

Help on built-in function max in module __builtin__:

max(...)

max(iterable[, key=func]) -> value

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

max_item = max(a_list, key=operator.itemgetter(1))
tgray
+1  A: 

Use the max() function or do it FP style:

reduce(lambda max, c: max if c <= max else c, [1, 6, 9, 2, 4, 0, 8, 1, 3])
Emil Ivanov