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

3 Answers 3

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']
Sign up to request clarification or add additional context in comments.

7 Comments

@JonClements: This was with me having to look up the keyword argument name again. :-P
Perfect :) I had no idea it could be so simple.
But the problem is, it only accepts integers to be summed. I have different type of values in my lists.
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.
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)).
|
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]]

Comments

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`

1 Comment

Welcome to Stack Overflow! Code-only answers are not particularly helpful. Please add some descriptions of how this code solves the problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.