- itertools.groupby
:
import itertools
a=[1,2,3,4,5,2,3,1,2,3,4,5,1,5,5,3,2,1,3,1]
new_a = [(a, list(b)) for a, b in itertools.groupby(a, key=lambda x:x == 1)]
final_a = list(itertools.chain(*[[-999] if a else [-999, -999, *b[2:]] for a, b in new_a]))
:
[-999, -999, -999, 4, 5, 2, 3, -999, -999, -999, 4, 5, -999, -999, -999, 3, 2, -999, -999, -999, -999]
: Python2:
import itertools
a=[1,2,3,4,5,2,3,1,2,3,4,5,1,5,5,3,2,1,3,1]
new_a = [(a, list(b)) for a, b in itertools.groupby(a, key=lambda x:x == 1)]
final_a = list(itertools.chain(*[[-999] if a else [-999, -999]+b[2:] for a, b in new_a]))