Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to print a nested list with the highest value in Python

I have a a nested list and I'm trying to get the sum and print the list that has the highest numerical value when the individual numbers are summed together

x = [[1,2,3],[4,5,6],[7,8,9]]
highest = list()

for i in x:
    highest.append(sum(i))

for ind, a in enumerate(highest):
    if a == max(highest):
        print(x[ind])

I've been able to print out the results but I think there should be a simple and more Pythonic way of doing this (Maybe using a list comprehension).

How would I do this?

like image 235
danidee Avatar asked Apr 20 '15 23:04

danidee


1 Answers

How about:

print(max(x, key=sum))

Demo:

>>> x = [[1,2,3],[4,5,6],[7,8,9]]
>>> print(max(x, key=sum))
[7, 8, 9]

This works because max (along with a number of other python builtins like min, sort ...) accepts a function to be used for the comparison. In this case, I just said that we should compare the elements in x based on their individual sum and Bob's our uncle, we're done!

like image 121
mgilson Avatar answered Sep 19 '22 12:09

mgilson