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.
import itertools
[ list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0] ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With