How to list a list in adjacent groups of nonzero integers in Python

He does not seem to have found a clue for this online and cannot figure it out himself:

How would I go about trimming a list to return a list of fragments of adjacent nonzero integers. i.e:

data = [3, 7, 4, 0, 1, 3, 7] 

and I want to create:

 slices = [[3, 7, 4], [1, 3, 7]] 

I tried various methods of iterating through the list, leaning towards the generator, which allows me to know when adjacent groups start and stop, checking if there are 0 before or after, but then I'm a bit of a dead end.

+5
python
source share
5 answers
 import itertools [ list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0] ] 
+11
source share

Take a look at itertools.groupby:

 >>> data = [3, 7, 4, 0, 1, 3, 7, 4, 0, 5] >>> a=[list(i[1]) for i in itertools.groupby(data, key=lambda i:i==0)] >>> a [[3, 7, 4], [0], [1, 3, 7, 4], [0], [5]] >>> [i for i in a if i != [0]] [[3, 7, 4], [1, 3, 7, 4], [5]] 
+5
source share
 def split_on_zero(data): start = 0 for (i, n) in enumerate(data): if n == 0: yield data[start:i] start = i + 1 yield data[start:] >>> list(split_on_zero([3, 7, 4, 0, 1, 3, 7])) [[3, 7, 4], [1, 3, 7]] >>> list(split_on_zero([0, 1, 2, 0, 3, 4, 5, 0])) [[], [1, 2], [3, 4, 5], []] 
+3
source share

Here is a basic solution that you can also try:

 data = [1, 0, 3, 7, 4, 1, 3, 7] def get_zero_sliced(inputList): res = [] prev = 0 for i,x in enumerate(data): if x == 0 and i != 0: res.append(data[prev:i]) prev = i + 1 if i == len(data)-1 and prev != i: res.append(data[prev:]) return res get_zero_sliced(data) 
+1
source share

The generator will work. Here is one, but there are probably other ways to do this. I called it x because I don’t have a good name right now (a good name requires some thought, so think about it).

 def x(iterator): result = [] for i in iterator: if i != 0: result.append(i) elif result: yield result result = [] if result: yield result 
0
source share

All Articles