Python: replace zeros with previous nonzero value

I would like to take a list of numbers in Python and replace all zeros with a previous non-zero value, for example. [1, 0, 0, 2, 0]must give [1,1,1,2,2]. I know that the first entry in the list is nonzero, so initialization should not be a problem. I can do this in a loop, but is there a more pythonic way to do this?

To clarify: this should work with any number list, for example. [100.7, 0, -2.34]must become [100.7, 100.7, -2.34].

+4
source share
6 answers

This can be done in a rather 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]

It only works if there is a previous nonzero value (i.e., a failure if a starts at 0).

,

+3

, none-zero:

def val(x,z=[0]):
   if x:
     z[0] = x
   return z[0]

[val(x) for x in a]

, [1, 1, 1, 2, 2]

+2

3.3 accumulate:

>>> from itertools import accumulate
>>> seq = [1, 0, 0, 2, 0]
>>> list(accumulate(seq, lambda x,y: y if y else x))
[1, 1, 1, 2, 2]
>>> seq = [100.7, 0, -2.34]
>>> list(accumulate(seq, lambda x,y: y if y else x))
[100.7, 100.7, -2.34]

(, or, , .)

+1

, , . ...

>>> my_list = [1, 0, 0, 2, 0]

>>> def set_sentinel(x):   
...     global sentinel
...     sentinel = x
...     return False
... 

>>> [set_sentinel(elem) or elem if elem else sentinel for elem in my_list]    
[1, 1, 1, 2, 2]
0

, for, . , .

>>> l = [1, 0, 0, 2, 0]
>>> [l[i] if l[i] else filter(lambda x: x > 0, l[:i])[-1] for i in range(len(l))]
[1, 1, 1, 2, 2]

, , .

0

. . . , , .

for i in range(1, len(a)):
  if a[i] == 0:
    a[i] = a[i-1]

I have seen many atrocities committed in the name of being "Pythonic". Choose carefully based on what best expresses your intentions. Do not blindly optimize the smallest lines of code or the smartest implementation.

0
source

Source: https://habr.com/ru/post/1528976/


All Articles