Reputation: 875
How can I add column values in a two dimenstional array? For example
[[11.9, 12.2, 12.9],
[15.3, 15.1, 15.1],
[16.3, 16.5, 16.5],
[17.7, 17.5, 18.1]]
I want it to result to:
[61.2,61.3,62.6]
I have tried this so far:
Btotals.append(sum(float(x)) for x in zip(totals))
However it gave me this:
[<generator object <genexpr> at 0x02A42878>]
Upvotes: 1
Views: 2919
Reputation: 74
You need to unpack the argument to zip first.
a = [[11.9, 12.2, 12.9],
[15.3, 15.1, 15.1],
[16.3, 16.5, 16.5],
[17.7, 17.5, 18.1]]
result = [sum(x) for x in zip(*a)]
>>> [61.2, 61.3, 62.6]
Upvotes: 1
Reputation: 2093
If array
is a variable containing your 2d array, try
[sum([row[i] for row in array]) for i in range(len(array[0]))]
Upvotes: 0