Hanfei Sun Hanfei Sun - 28 days ago 19
Python Question

array sums and statistics

Input:

a[0] = [0, 1, 2]
a[1] = [0, 2, 2]
a[2] = [100, 200, 300]


Output1:

output1
>> [100, 203, 304]


Output2:

output2
>> [{0:2, 100:1}, {1:1, 2:1, 200:1}, {2:2, 300:1}]


In other words, output1 calculate the sum of each column, and output2 statistics the occurrence of each number in each column.

(Actually, a is a matrix of 4000*400000)
Does anyone have ideas how to do this efficiently in Python?

Answer

for output1 you can calculate sum for each row of transposed matrix:

map(sum, zip(*a))

for output2 you can use collections.Counter applied to each column:

from collections import Counter
output = [Counter(col) for col in zip(*a)]

Or:

output = map(Counter, zip(*a))
Comments