How To Sum Lists In Lists Pairwise In Python And Put This Sum In A New List
the question is pretty clear but an example: a = [[1,2],[3,4],[5,6],[7,8]] then the list I want to make is: a_new = [ 1+3+5+7 , 2+4+6+8] The lists within the list are always of t
Solution 1:
Use the zip()
function to transpose your input lists from rows to columns, then sum()
those columns:
[sum(col) for col inzip(*a)]
Demo:
>>>a = [[1,2],[3,4],[5,6],[7,8]]>>>zip(*a)
[(1, 3, 5, 7), (2, 4, 6, 8)]
>>>[sum(col) for col inzip(*a)]
[16, 20]
Solution 2:
Solution 3:
Instead of using map()
, zip()
, or reduce()
, here is a pure list comprehension method using list concatenation:
[sum([x for x, y in a])]+[sum([y for x, y in a])]
>>>a = [[1,2],[3,4],[5,6],[7,8]]>>>a_new = [sum([x for x, y in a])]+[sum([y for x, y in a])]>>>a_new
[16, 20]
>>>
Post a Comment for "How To Sum Lists In Lists Pairwise In Python And Put This Sum In A New List"