For this given list:
a = [1, 0, 0, 1, 1, 1, 3, 0,
1, 1, 4, 2, 1, 1, 2, 1, 1, 1, 1,
0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 5]
I would like to split the list into sublists of zeros and nonzero values to have the desired output of
a = [[1], [0,0], [1,1,1,3], [0],
[1,1,3,2,1,1,2,1,1,1,1,],
[0], [1], [0], [1,1,1], [0,0,0], [1,5]]
I know how to split a list into a certain length of sublists, but I don't think I can use that method here...
You can use itertools.groupby
from itertools import groupby
a = [list(g) for k, g in groupby(a, lambda x:x>0)]
groupby(a, lambda x:x>0) groups successive 0 values or non-zero values together.
Above only handles non-negative values. Improvement from FreddyMcloughlan comment to handle all integers.
a = [list(g) for k, g in groupby(a, lambda x: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