Sum A List Of Lists To Get A Sum List Python
I'm trying to create a define a helper function that sums a list of lists to get a sum list. For example: [[1,2,3],[1,2,3],[2,3,4]] Would come out as: [4,7,10] I found this on
Solution 1:
Just put the list comprehension inside the function. (with return
)
>>>defaddhours(listoflists):...return [sum(lst) for lst inzip(*listoflists)]...>>>addhours([[1,2,3],[1,2,3],[2,3,4]])
[4, 7, 10]
Why your code does not work?
defaddhours(listoflists):
forlistinzip(*listoflists):
newsum = sum (list) # <---- This statement overwrites newsumreturn newsum # returns the last sum.
You need a list to hold sums as items.
defaddhours(listoflists):
result = []
for lst inzip(*listoflists):
result.append(sum(lst)) # Append to the list instead of overwriting.return result
BTW, don't use list
as a variable name. It shadows builtin function list
.
Solution 2:
Since the function is quite small, you could also use an anonymous definition:
>>>addhours = lambda l: [sum(i) for i inzip(*l)]>>>addhours([[1,2,3],[1,2,3],[2,3,4]])>>>[4,7,10]
Post a Comment for "Sum A List Of Lists To Get A Sum List Python"