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

I have a nested list and I'm trying to get the sum and print the list with the highest numerical value when 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 was able to print the results, but I think there should be an easier and more Pythonic way to do this (possibly using list comprehension).

How can I do it?

+6
source share
1 answer

What 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 built-in python like min , sort ...) accepts a function that will be used for comparison. In this case, I just said that we should compare the elements in x based on their individual sum and Bob of our uncle, we are done!

+13
source

Source: https://habr.com/ru/post/985558/


All Articles