hpnk85 hpnk85 - 1 year ago 77
Python Question

count number of events in an array python

I have the following array:

a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0]

Each time I have a '1' or a series of them(consecutive), this is one event. I need to get, in Python, how many events my array has. So in this case we will have 5 events (that is 5 times 1 or sequences of it appears). I need to count such events in order to to get:

b = [5]


Answer Source

You could use itertools.groupby (it does exactly what you want - groups consecutive elements) and count all groups which starts with 1:

In [1]: from itertools import groupby

In [2]: a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0]

In [3]: len([k for k, _ in groupby(a) if k == 1])
Out[3]: 5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download