在列表中将None替换为最左边的非none值

tlr*_*rrd 6 python

特定

a = [None,1,2,3,None,4,None,None]
Run Code Online (Sandbox Code Playgroud)

我想要

a = [None,1,2,3,3,4,4,4]
Run Code Online (Sandbox Code Playgroud)

目前我有强迫它:

def replaceNoneWithLeftmost(val):
    last = None
    ret = []
    for x in val:
        if x is not None:
            ret.append(x)
            last = x
        else:
           ret.append(last)
    return ret
Run Code Online (Sandbox Code Playgroud)

最后,我想去

a = [1,1,2,3,3,4,4,4]
Run Code Online (Sandbox Code Playgroud)

通过从右到左运行.目前我有

def replaceNoneWithRightmost(val):
    return replaceNoneWithLeftmost(val[::-1])[::-1]
Run Code Online (Sandbox Code Playgroud)

我并不挑剔现场或创建一个新的清单,但现在这闻到了我的气味.我看不到存储临时'last'值并使用map/lambda的方法,而且没有别的想法.

DSM*_*DSM 5

IIUC,您可以itertools.accumulate用来生成前向填充:

>>> from itertools import accumulate
>>> a = [None,1,2,3,None,4,None,None]
>>> list(accumulate(a, lambda x,y: y if y is not None else x))
[None, 1, 2, 3, 3, 4, 4, 4]
Run Code Online (Sandbox Code Playgroud)

  • 它只是在python 3中! (2认同)

Pad*_*ham 3

a = [None,1,2,3,None,4,None,None]

start = next(ele for ele in a if ele is not None)
for ind, ele in enumerate(a):
    if ele is None:
        a[ind] = start
    else:
        start = ele
print(a)
[1, 1, 2, 3, 3, 4, 4, 4]
Run Code Online (Sandbox Code Playgroud)

如果第一个元素为 None,您也只需将 start 设置为一个值:

if a[0] is None:
   start = next(ele for ele in a if ele is not None)
for ind, ele in enumerate(a):
    if ele is None:
        a[ind] = start
    else:
        start = ele
print(a)
Run Code Online (Sandbox Code Playgroud)