首页 > 解决方案 > 替换列表中的 None 值时如何处理边缘情况?

问题描述

我希望用前面的值替换列表中的 None 值,但考虑到第一个值为 None 或前面的值为 None 的边缘情况;如果第一个值为 None 它应该保持 None。因此,例如下面是人们期望的输入和输出:

[1,2,None,3,None] --> [1,2,2,3,3]
[None,1,2,2,None,None,3] --> [None,1,2,2,2,2,3]

我尝试了一些循环,但我不确定如何处理边缘情况:

myList = [1,None,1,2,None]
def replaceNone(myList):
    res = []
    for i in range(len(myList)):
        if myList[i] is not None:
            res.append(myList[i])
        else:
            res.append(myList[i-1])
    return res

replaceNone(myList)

标签: pythonarraysnonetype

解决方案


我会做类似的事情

new_list = [listA[index - 1] if i == None and index>= 1 else i for index, i in enumerate(listA)] 

例如:

listA = [1,2,None,3,None]
listB = [None, 2, 3, None, 4]


new_list = [listA[index - 1] if i == None and index>= 1 else i for index, i in enumerate(listA)] 
new_list2 = [listB[index - 1] if i == None and index>= 1 else i for index, i in enumerate(listB)] 

print(new_list)
print(new_list2)

输出:

[1, 2, 2, 3, 3] #listA
[None, 2, 3, 3, 4] #listB

这似乎是期望的行为


推荐阅读