How can I remove all zeros except x from them in each run of consecutive zeros in the list?

For every run of x or more consecutive zeros in a list in Python, I would like to handle all the zeros in the run, except for x of them. If x = 0 , then remove all zeros.

I was thinking of a Python function that took a list, L and a number, x , as inputs.

For example, let L = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8] .

  • If x = 0 , return L = [7, 12, 2, 27, 10, 8]
  • If x = 1 , return L = [7, 0, 12, 0, 2, 0, 27, 10, 0, 8]
  • If x = 2 , return L = [7, 0, 12, 0, 0, 2, 0, 0, 27, 10, 0, 0, 8]
  • If x = 3 , return L = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 8]
  • If x = 4 , return L = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8] (Same as the original L )
  • If x >= 5 , return the original L, since there are no runs of 5 or more consecutive zeros.

Any help would be truly appreciated.

+4
source share
3 answers

It is easy to do as a generator. Wrap your call in the list constructor if you want the new list to be deleted with zero launch.

 def compact_zero_runs(iterable, max_zeros): zeros = 0 for i in iterable: if i == 0: zeros += 1 if zeros <= max_zeros: yield i else: zeros = 0 yield i 
+8
source

Using groupby:

 def del_zeros(lst, n): lst = (list(j)[:n] if i else list(j) for i,j in itertools.groupby(lst, key=lambda x:x==0)) return [item for sublist in lst for item in sublist] 

And tests:

 >>> [del_zeros(L, i) for i in range(5)] [[7, 12, 2, 27, 10, 8], [7, 0, 12, 0, 2, 0, 27, 10, 0, 8], [7, 0, 12, 0, 0, 2, 0, 0, 27, 10, 0, 0, 8], [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 8], [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8]] 
+3
source
 from itertools import groupby, chain, islice from functools import partial from operator import eq def f(L, x): groups = groupby(L, partial(eq, 0)) return list(chain.from_iterable(islice(v, x) if k else v for k,v in groups)) 
+3
source

All Articles