Home > Software engineering >  Finding the highest sum of each list in a nested list and then printing the highest list
Finding the highest sum of each list in a nested list and then printing the highest list

Time:10-26

So I have this task to find the list with highest sum in a nested list and I'm stuck.So far I have tried :

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)

The output I get:

[[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

The Output I need:

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

CodePudding user response:

IIUC, you can do this with for-loop like below:

>>> 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]

You can do this with dictionary like below:

>>> 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]

CodePudding user response:

Your code looks way to complicated.

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

The for loop iterates over your input list L. Then the sum functions calculates the sum of the 4 sub lists and appends it to the output array.

If you then need the list with the highest sum, you can print the sub list at the index of the highest number in O.

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

CodePudding user response:

Instead of

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)

use this list_2 = [sum(i) for i in list_1]

  • Related