saud - 9 months ago 34

Python Question

I have a long boolean array:

`bool_array = [ True, True, True, True, True, False, False, False, False, False, True, True, True, False, False, True, True, True, True, False, False, False, False, False, False, False ]`

I need to figure out where the values flips, i.e., the addresses where sequences of

`True`

`False`

`index = [0, 5, 10, 13, 15, 19, 26]`

Is there an easy way to do without manually looping to check every ith element with the (i+1)th?

Answer

As a more efficient approach for large datasets, in python 3.X you can use `accumulate`

and `groupby`

function from `itertools`

module.

```
>>> from itertools import accumulate, groupby
>>> [0] + list(accumulate(sum(1 for _ in g) for _,g in groupby(bool_array)))
[0, 5, 10, 13, 15, 19, 26]
```