我正在寻找一种方法来填充列表中的na,其中包含python中的最后一个已知值。
示例:Input a = [1, 2, None, 4, 5, None, 5, 4, None, 7, None, None, None, None]
Output: [1, 2, 2, 4, 5, 5, 5, 4, 4, 7, 7, 7, 7,7]
如果第一个元素是None,那么我们必须用列表中的第一个非null元素替换它,然后执行上面的任务。
答案 0 :(得分:2)
a = [1, 2, None, 4, 5, None, 5, 4, None, 7, None, None, None, None]
b = [None, 2, None, 4, 5, None, 5, 4, None, 7, None, None, None, None]
c = [None, None, None, 4, 5, None, 5, 4, None, 7, None, None, None, None]
def fill_none(a):
for i, j in enumerate(a):
if j is None:
if i == 0:
a[0] = next(item for item in a if item is not None)
else:
a[i] = a[i-1]
return a
>>> print fill_none(a)
[1, 2, 2, 4, 5, 5, 5, 4, 4, 7, 7, 7, 7, 7]
>>> print fill_none(b)
[2, 2, 2, 4, 5, 5, 5, 4, 4, 7, 7, 7, 7, 7]
>>> print fill_none(c)
[4, 4, 4, 4, 5, 5, 5, 4, 4, 7, 7, 7, 7, 7]
答案 1 :(得分:0)
试试这个:
lis = [1, 2, None, 4, 5, None, 5, 4, None, 7, None, None, None, None]
for x in range(len(lis)):
if lis[0] == None:
lis[0] = 1
if lis[x] == None:
lis[x] = lis[x - 1]
print(lis)
输出= [1,2,2,4,5,5,5,4,4,7,7,7,7,7]