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 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].
x = 0, then return L = [7, 12, 2, 27, 10, 8]
x = 1, then return L = [7, 0, 12, 0, 2, 0, 27, 10, 0, 8]
x = 2, then return L = [7, 0, 12, 0, 0, 2, 0, 0, 27, 10, 0, 0, 8]
x = 3, then return L = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 8]
x = 4, then return L = [7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8] (Same as original L)x >= 5, then return original L as there are no runs of 5 or more consecutive zeros.Any help would be sincerely appreciated.
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 = 0
for i in iterable:
if i == 0:
zeros += 1
if zeros <= max_zeros:
yield i
else:
zeros = 0
yield i
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With