如何用以前的值替换列表中的无

Par*_*jan 13 python list-comprehension python-3.x

我想用之前的变量(对于所有连续的无)替换Nonein list。我用iffor(多行)做到了。有没有办法在一行中做到这一点?即,列表理解、Lambda 和/或地图

我的想法是使用列表理解,但我无法在列表理解中分配变量来设置以前的值。

我的项目中有一个类似的场景以None这种方式处理,问题是我不想为小功能编写 10 行代码。

def none_replace(ls):
    ret = []
    prev_val = None
    for i in ls:
        if i:
            prev_val = i
            ret.append(i)
        else:
            ret.append(prev_val)
    return ret

print('Replaced None List:', none_replace([None, None, 1, 2, None, None, 3, 4, None, 5, None, None]))
Run Code Online (Sandbox Code Playgroud)

输出:

Replaced None List: [None, None, 1, 2, 2, 2, 3, 4, 4, 5, 5, 5]

Sel*_*cuk 12

在 Python 3.8 或更高版本中,您可以使用赋值运算符执行此操作

def none_replace(ls):
    p = None
    return [p:=e if e is not None else p for e in ls]
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以利用可变列表

x =[None, None, 1, 2, None, None, 3, 4, None, 5, None, None]
for i,e in enumerate(x[:-1], 1):
    if x[i] is None:
        x[i] = x[i-1]
print(x)
Run Code Online (Sandbox Code Playgroud)

输出

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


Myk*_*tko 5

您可以使用该函数accumulate()和运算符or

from itertools import accumulate

list(accumulate(lst, lambda x, y: y or x))
# [None, None, 1, 2, 2, 2, 3, 4, 4, 5, 5, 5]
Run Code Online (Sandbox Code Playgroud)

在此解决方案中,您获取该元素y和前一个元素x,并使用运算符对它们进行比较or。如果yNone则取前一个元素x;否则,你就拿y。如果两者都是None你得到的None

  • 使用“python”库和一行的另一种最佳方法:)如果有机会的话,您是否还可以在此处添加有关“accumulate”如何工作的解释? (2认同)
  • @MykolaZotko https://repl.it/repls/WonderfulLatePython#main.py (2认同)