gpt4 book ai didi

python - 用最左边的非无值替换列表中的无

转载 作者:太空狗 更新时间:2023-10-29 23:58:32 24 4
gpt4 key购买 nike

给定

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

我愿意

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

目前我用暴力破解它:

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]

我对就地或创建新列表并不挑剔,但现在这对我来说很奇怪。我看不到存储临时“最后”值和使用 map/lambda 的方法,并且没有想到其他任何东西。

最佳答案

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]

关于python - 用最左边的非无值替换列表中的无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31256159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com