How Can I Delete All Zeros Except For X Of Them In Every Run Of Consecutive Zeros Within A List?
For every run of x or more consecutive zeros in a list in Python, I would like to del all zeros in the run except for x of them. If x = 0, then delete all zeros. I was thinking of
Solution 1:
This is easy to do as a generator. Wrap your call to it in a list
constructor if you want a fresh list with the zero-runs removed.
def compact_zero_runs(iterable, max_zeros):
zeros = 0for i in iterable:
if i == 0:
zeros += 1if zeros <= max_zeros:
yield i
else:
zeros = 0yield i
Solution 2:
Using groupby:
defdel_zeros(lst, n):
lst = (list(j)[:n] if i else list(j)
for i,j in itertools.groupby(lst, key=lambdax:x==0))
return [item for sublist in lst for item in sublist]
And the 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]]
Solution 3:
from itertools import groupby, chain, islice
from functools import partial
from operator import eq
deff(L, x):
groups = groupby(L, partial(eq, 0))
returnlist(chain.from_iterable(islice(v, x) if k else v for k,v in groups))
Post a Comment for "How Can I Delete All Zeros Except For X Of Them In Every Run Of Consecutive Zeros Within A List?"