Given
lst_1 = [1, 1, 1, 0, 1, 1]
lst_2 = [0, 1, 1, 0, 1, 1, 0, 0, 1]
lst_3 = [0, 1, 1, 0, 1, 1, 0, 0, 1, 1]
Code
def compress_values(seq, value=1):
"""Yield a value in isolation."""
for here, nxt in zip(seq, seq[1:]):
if here == nxt == value:
continue
else:
yield here
yield nxt
Demo
assert [1, 0, 1] == list(compress_values(lst_1))
assert [0, 1, 0, 1, 0, 0, 1] == list(compress_values(lst_2))
assert [0, 1, 0, 1, 0, 0, 1] == list(compress_values(lst_3))
Details
Slide a two-tuple window. If values are equal to each other and the target value
, skip. Otherwise yield values.
An alternative, more general approach:
import itertools as it
def squash(seq, values=(1,)):
"""Yield singular values in isolation."""
for k, g in it.groupby(seq):
if k in values:
yield k
else:
yield from g