mourad mourad - 7 months ago 11
Python Question

Cumulative occurence count

I have a number of lists that have 2 dimensions and I need to get
cumulative count elements:

a=[1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4]
b=[1,1,1,2,2,2,3,3,3,4]
c=[1,2,2,2,3,4]
c=[]
for i in a:
for x,y in enumerate(c):
print i
if y[0]==i:
y[1]+=1
else:
c.append([i,1])

I need to obtain:
[[1,9],[2,10],[3,7]...]

Answer

Another solution, only for Python 3.5+:

>>> from collections import Counter
>>> Counter([*a, *b, *c])
Counter({2: 10, 1: 9, 3: 8, 4: 5})

If you really need the list of lists format, the conversion goes like this:

>>> [list(x) for x in Counter([*a, *b, *c]).items()]
[[1, 9], [2, 10], [3, 8], [4, 5]]