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