将列表中的None替换为最左边的None-None值

2024-09-30 16:41:36 发布

您现在位置:Python中文网/ 问答频道 /正文

给予

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

我想

^{pr2}$

目前,我已经用暴力强迫它:

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

最后,我想

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

从右向左跑。目前我有

def replaceNoneWithRightmost(val):
    return replaceNoneWithLeftmost(val[::-1])[::-1]

我不在乎是否到位或创建一个新的列表,但现在我觉得这很难闻。我看不到一种方法来存储一个临时的“last”值并使用map/lambda,其他的都没有想到。在


Tags: innoneforreturnifisdefnot
3条回答

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

如果第一个元素为“无”,则只需将start设置为值:

^{pr2}$

这里有一些代码可以在适当的地方做你想做的事情,如果你不想让它就位,那么只需传递它list(my_list),而不是my_list。在

def replaceNoneWithLeftmost(val):
    for i in range(len(val)):
        if val[i] is None:
            for j in range(i-1, -1, -1):
                if val[j] is not None:
                    val[i] = val[j]
                    break
    for i in range(len(val)):
        if val[i] is None:
            for j in range(i+1, len(val)):
                if val[j] is not None:
                    val[i] = val[j]
                    break
    return val

另外,如果使用python2,请使用xrange而不是{}。在

相关问题 更多 >