Home > Software design >  How to split list into sublists of zeros and nonzero values
How to split list into sublists of zeros and nonzero values

Time:05-11

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 dont think I can use that method here...

CodePudding user response:

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.

CodePudding user response:

You can just iterate over each value, and keep a buffer c and append the buffer to b when the element changes from 0 to a number > 0:

b = []
c = [a[0]]

for i in a[1:]:
    if (c[-1] > 0 and i > 0) or (c[-1] == 0 and i == 0):
        # Continue run
        c.append(i)
    else:
        b.append(c)
        c = [i]

b.append(c)

i.e. The conditional checks to see if the buffer c has changed from a non-zero array to a > 0 array (and vice versa) and if it has not changed, you extend the buffer. When it has changed, append c to b (where b is the final array) then change the buffer to the next value i.

  • Related