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?
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!
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