Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: replace zeros by previous nonzero value

Tags:

python

I would like to take a list of numbers in Python and replace all zeros by the previous nonzero value, e.g. [1, 0, 0, 2, 0] should give [1,1,1,2,2]. I know that the first entry in the list is nonzero so initialisation should not be a problem. I can do it in a loop but is there a more pythonic way of doing this?

To clarify: This should work on any numeric list, e.g. [100.7, 0, -2.34] should become [100.7, 100.7, -2.34].

like image 877
Anne Avatar asked Mar 21 '23 10:03

Anne


1 Answers

This can be done in a quite short loop:

a = [1, 0, 0, 2, 0]
b = []
for i in a:
    b.append(i if i else b[-1])
print b
# [1, 1, 1, 2, 2]

Works only if there is a previous non-zero value (i.e. fails if a starts with 0).

As there is no way to reference a list comprehension from inside, this cannot be made a list comprension

like image 100
njzk2 Avatar answered Mar 31 '23 17:03

njzk2