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)
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With