给予
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,其他的都没有想到。在
IIUC,您可以使用
itertools.accumulate
生成前向填充:如果第一个元素为“无”,则只需将start设置为值:
^{pr2}$这里有一些代码可以在适当的地方做你想做的事情,如果你不想让它就位,那么只需传递它
list(my_list)
,而不是my_list
。在另外,如果使用python2,请使用}。在
xrange
而不是{相关问题 更多 >
编程相关推荐