Python|列表列表中列表元素的最大总和
给定列表中的列表,找到列表中列表元素的最大总和。
例子:
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
方法一:列表中列表的遍历
我们可以遍历列表中的列表,并对给定列表中的所有元素求和,并通过max函数获得列表中所有元素之和的最大值。
# 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
方法二:列表遍历
只遍历外层列表,使用 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函数
sum(max(list1, key=sum))
max()函数的上述语法允许我们使用key=sum找到列表中列表的总和。 max(list1, key=sum) ,这会找到元素总和最大的列表,然后sum(max(list1, key=sum))返回该列表的总和。
# 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