How to find the list in a list of lists whose sum of elements is the greatest?

I have a list of lists:

x = [[1,2,3], [4,5,6], [7,8,9], [2,2,0]]

I want to get the list whose sum of its elements is the greatest in the list. In this case [7,8,9].

I'd rather have a fancy map or lambda or list comprehension method than a for/while/if loop.

Best Regards


max takes a key argument, with it you can tell max how to calculate the value for each item in an iterable. sum will do nicely here:

max(x, key=sum)


>>> x = [[1,2,3], [4,5,6], [7,8,9], [2,2,0]]
>>> max(x, key=sum)
[7, 8, 9]

If you need to use a different method of summing your items, you can specify your own functions too; this is not limited to the python built-in functions:

>>> def mymaxfunction(item):
...     return sum(map(int, item))
>>> max([['1', '2', '3'], ['7', '8', '9']], key=mymaxfunction)
['7', '8', '9']

For completeness and as @Martijn beat me to the most elegant answer - I'll just throw in the option before the key= parameter was available in Python (but if you're using < 2.5 - you should really upgrade) and how ugly it use to be:

x = [[1,2,3], [4,5,6], [7,8,9], [2,2,0]]
with_idx = ( (sum(v), i) for i,v in enumerate(x))
print x[max(with_idx)[1]]

Need Your Help

Change UIPopoverView background + arrow color

ios uiview swift ios8 uipopoverbackgroundview

Is there a way to simply change the UIPopoverView background color (including its arrow) on iOS8?