10

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

alwbtc
  • 28,057
  • 62
  • 134
  • 188

3 Answers3

25

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']
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @JonClements: This was *with* me having to look up the keyword argument name again. :-P – Martijn Pieters Jul 17 '12 at 09:39
  • Perfect :) I had no idea it could be so simple. – alwbtc Jul 17 '12 at 09:40
  • But the problem is, it only accepts integers to be summed. I have different type of values in my lists. – alwbtc Jul 17 '12 at 09:45
  • 1
    It's easy enough to customize the function used for `key`, isn't it? If you have trouble with that, post a new question here on SO and we can help you again. – Martijn Pieters Jul 17 '12 at 09:46
  • replace `sum` with your own function, either `max(x, key=lambda x: some expression)` or define a new function (`def foobar(x): return some calculation`) and use that for the `key` (`max(x, key=foobar)`). – Martijn Pieters Jul 17 '12 at 09:50
  • does the custom function have to take any arguments? If yes, how many? – alwbtc Jul 17 '12 at 10:00
  • See my updated answer; it takes one argument. This is documented on the [documentation page for max](http://docs.python.org/library/functions.html#max) as well. – Martijn Pieters Jul 17 '12 at 10:03
0

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]]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0
num = [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]]
 
index = 0
max_index = 0
sum_max = 0
for list in num:
>>>>sum_list = 0
>>>>for x in list:
>>>>>>>>sum_list += x
>>>>if sum_list > sum_max:
>>>>>>>>sum_max = sum_list
>>>>>>>>max_index = index
>>>>index += 1
print(num[max_index])`enter code here`
  • Welcome to Stack Overflow! Code-only answers are not particularly helpful. Please add some descriptions of how this code solves the problem. – Sven Eberth Jul 02 '21 at 21:28