给定列表中的列表,求列表中列表元素的最大和。
null
例如:
Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Output : 12
方法1:遍历列表中的列表
我们可以遍历列表中的列表,并对给定列表中的所有元素求和 最大函数 获取列表中所有元素之和的最大值。
# Python program to find the # list in a list of lists whose # sum of elements is the highest # using traversal def maximumSum(list1): maxi = 0 # traversal in the lists for x in list1: sum = 0 # traversal in list of lists for y in x: sum + = y maxi = max ( sum , maxi) return maxi # driver code list1 = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 10 , 11 , 12 ], [ 7 , 8 , 9 ]] print maximumSum(list1) |
输出:
33
方法2:遍历列表
仅遍历外部列表,并使用 sum() 函数,找到所有列表的总和,并获得所有计算总和的最大值。
# Python program to find the # list in a list of lists whose # sum of elements is the highest # using sum and max function and traversal def maximumSum(list1): maxi = 0 # traversal for x in list1: maxi = max ( sum (x), maxi) return maxi # driver code list1 = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 10 , 11 , 12 ], [ 7 , 8 , 9 ]] print maximumSum(list1) |
输出:
33
方法3:求和与最大函数
sum(max(list1, key=sum))
max()函数的上述语法允许我们使用 key=sum . 最大值(列表1,键=和) ,这会找到元素和最大的列表,然后 总和(最大值(列表1,键=总和)) 返回该列表的总和。
# Python program to find the # list in a list of lists whose # sum of elements is the highest # using sum and max function def maximumSum(list1): return ( sum ( max (list1, key = sum ))) # driver code list1 = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 10 , 11 , 12 ], [ 7 , 8 , 9 ]] print maximumSum(list1) |
输出:
33
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END