Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice list into contiguous groups of non-zero integers in Python

Tags:

python

Can't seem to find a clue to this online and can't figure it out myself so:

How would I go about slicing a list so that I return a list of slices of contiguous non-zero integers. ie:

data = [3, 7, 4, 0, 1, 3, 7]

and I want to produce:

slices = [[3, 7, 4], [1, 3, 7]]

I have tried various methods of iterating through the list, have been leaning towards a generator that lets me know when the contiguous groups start and stop, by testing if there is a 0 before or after, but then I am a bit stumped.

like image 721
emergence Avatar asked Jul 20 '11 11:07

emergence


1 Answers

import itertools
[ list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0] ]
like image 56
Karoly Horvath Avatar answered Oct 19 '22 23:10

Karoly Horvath