查找嵌套列表中每个列表的最高总和,然后打印最高列表

Finding the highest sum of each list in a nested list and then printing the highest list

所以我的任务是在嵌套列表中找到总和最高的列表,我 stuck.So 到目前为止我已经尝试过了:

list_1 = []
list_2 = []
total = 0
limit = int(input('Number of Lists: '))

for i in range(0,limit):
    numbs = [int(x) for x in input('Enter List: ').split()]
    list_1.append(numbs)
for y in range(0, len(list_1[0])):
    for z in range(0, len(list_1)):
        total = total + list_1[z][y]
        list_2.append(total)
print(list_1)
print(list_2)

我得到的输出:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
[22, 48, 78]
Why is there even three values? I have four sublists

我需要的输出:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
[6, 15, 24, 33]

IIUC,您可以像下面这样使用 for-loop 来做到这一点:

>>> list_1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> list_2 = [sum(l) for l in list_1]
>>> list_2
[6, 15, 24, 33]

# finding max in each list
>>> lst_mx = [max(l) for l in list_1]
>>> lst_mx
[3, 6, 9, 12]

# list have maximun sum
>>> max(list_1, key=sum)
[10, 11, 12]

您可以使用 dictionary 执行此操作,如下所示:

>>> dct = {sum(l) : l for l in list_1}
>>> dct
{6: [1, 2, 3], 15: [4, 5, 6], 24: [7, 8, 9], 33: [10, 11, 12]}

>>> dct[max(dct)]
[10, 11, 12]

您的代码看起来太复杂了。

L = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
O = []
for i in L:
    O.append(sum(i))
print(O)

for 循环遍历您的输入列表 L。然后 sum 函数计算 4 个子列表的总和并将其附加到输出数组。

如果您随后需要总和最高的列表,您可以在 O 中最大数字的索引处打印子列表。

maxIndex = O.index(max(O))
print(L[maxIndex])

而不是

for y in range(0, len(list_1[0])):
    for z in range(0, len(list_1)):
        total = total + list_1[z][y]
        list_2.append(total)

使用这个list_2 = [sum(i) for i in list_1]