Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split list into sublists of zeros and nonzero values

Tags:

python

list

split

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...

like image 758
Duke Kim Avatar asked Dec 10 '25 21:12

Duke Kim


1 Answers

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)]
like image 195
DarrylG Avatar answered Dec 13 '25 11:12

DarrylG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!