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]
.
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
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