Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract separate non-zero blocks from array

having an array like this for example:

[1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1]

What's the fastest way in Python to get the non-zero elements organized in a list where each element contains the indexes of blocks of continuous non-zero values?

Here the result would be a list containing many arrays:

([0, 1, 2, 3], [9, 10, 11], [14, 15], [20, 21])
like image 844
Mehdi Avatar asked Jul 21 '15 16:07

Mehdi


Video Answer


1 Answers

>>> L = [1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1]
>>> import itertools
>>> import operator
>>> [[i for i,value in it] for key,it in itertools.groupby(enumerate(L), key=operator.itemgetter(1)) if key != 0]

[[0, 1, 2, 3], [9, 10, 11], [14, 15], [20, 21]]
like image 124
ovgolovin Avatar answered Sep 20 '22 16:09

ovgolovin