Python list traversal with gaps

python

Solution

`itertools.groupby()` is perfect for this:

from itertools import groupby
my_list = [[1,2,3,1,2],[1,0,3,1,2],[1,0,0,0,2],[1,0,3,0,2]]
new_list = [[len(list(g)) for k, g in groupby(inner, bool) if k] for inner in my_list]

Result:

>>> new_list
[[5], [1, 3], [1, 1], [1, 1, 1]]

The result contains the length of each non-zero chunk for each sublist, so for example `[1,0,3,1,2]` gives `[1,3]`, so there are two chunks (one gap). This matches your second output format.

Problem

Hi I have a multidimensional list such as: ``` my_list = [[1,2,3,1,2],[1,0,3,1,2],[1,0,0,0,2],[1,0,3,0,2]] ``` where 0 represents a gap between two pieces of data. What I need to do is iterate through the list and keep track of how many gaps are in each sublist and throw away the zeros. I think the best way is to break each sublist into chunks where there are zeros so I end up with smaller lists of integers and a number of gaps. Ideally, to form a new list which tells me the length of each chunk and number of gaps (i.e. chunks -1), such as: ``` new_list = [[5, 0], [[1, 3], 1], [[1, 1], 1], [[1, 1, 1], 2]] ``` or probably better: ``` new_list = [[5], [1, 3], [1, 1], [1, 1, 1]] ``` and I will know that the gaps are equal to len(chunk). EDIT: However, leading and trailing zeros do not represent gaps. i.e. [0,0,1,2] represents one continuous chunk. Any help much appreciated.

Original source