How can I sum multiple list elements at the same time? For example, something like this in Python:
Our lists (input):
[3, 3, 1, 1, 1, 1, 1]
[1, 1, 4, 5, 6, 7, 8]
Output:
[4, 4, 5, 6, 7, 8, 9]
Note: we don't know how many list will be given to us.
CodePudding user response:
This should do the job
l1 = [3, 3, 1, 1, 1, 1, 1]
l2 = [1, 1, 4, 5, 6, 7, 8]
l3 = [sum(t) for t in zip(l1, l2)]
print(l3)
CodePudding user response:
As we don't know how many lists there will be, and I assume their lengths could be different, using the zip_longest
function from itertools
is the perfect tool:
from itertools import zip_longest
l1 = [3, 3, 1, 1, 1, 1, 1]
l2 = [1, 1, 4, 5, 6, 7, 8]
l3 = [1, 1, 4, 5, 6, 7, 8, -1]
l4 = [-105]
lists = [l1,l2,l3,l4]
summed = list(map(sum,zip_longest(*lists,fillvalue=0)))
print(summed)
Output:
[-100, 5, 9, 11, 13, 15, 17, -1]
CodePudding user response:
This can be done very easily and efficiently using pandas.
lists = [[3, 3, 1, 1, 1, 1, 1], [1, 1, 4, 5, 6, 7, 8]]
df = pd.DataFrame(data=lists)
out = df.sum().tolist()
print(out):
[4, 4, 5, 6, 7, 8, 9]
It should work with any number of lists.
CodePudding user response:
If you have varying number of list as input , you can try the below.,
note : input the numbers in list as comma-seperated values
Console
1,2,3
2,3,1
[3, 5, 4]
import pandas as pd
ls = []
while True:
inp = input()
if inp == "":
break
ls.append(list(map(int,inp.split(","))))
df = pd.DataFrame(data=ls)
out = df.astype(int).sum().tolist()
print(out)