Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

max

sum

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

like image 308
alwbtc Avatar asked Jul 17 '12 09:07

alwbtc


1 Answers

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)

Demo:

>>> 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']
like image 152
Martijn Pieters Avatar answered Oct 10 '22 07:10

Martijn Pieters