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.
>>> 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)]