list - select subarrays delimited by zeros in python -


given list like:

a = [18, 7, 0, 0, 0, 9, 12, 0, 0, 11, 2, 3, 3, 0, 0, 7, 8] 

is there simple way create subarrays, elements separated zeros (or @ least nans)? mean, like:

a1 = [18, 7] a2 = [9, 12] a3 = [11, 2, 3, 3] a4 = [7, 8] 

i've written:

q=0 in range(0,len(a)):     if a[i]-a[i-1] < 1:         q=q+1 

to retrieve number of zeros-packets present in list. need populate subarrays, long encounter them through list... maybe split function? thank in advance.

well, itertools has solution you: groupby(list, filter).

if want group zeroes, start doing:

b = itertools.groupby(a, lambda x:x == 0) 

the lambda expression "decides" of values should separator. separate nones using lambda x: x == none (for example). return iterable object. so, using list comprehension, let's iterate through (every iteration gives 2 values tuple):

c = [(i, list(j)) i, j in b] # j cast list because it's object, not list. 

output like:

[(false, [18, 7]), (true, [0]), (true, [0]), (true, [0]), ... ]

now, every list j separator has value true i. can filter it:

c = [list(j) i, j in b if not i] 

now, result 2d list:

[[18, 7], [9, 12], [11, 2, 3, 3], [7, 8]]

so 1 liner function:

def splitarr():     return [list(j) i, j in itertools.groupby(a, lambda x:x == 0) if not i] 

Comments