python - 替换列表中的 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)
解决方案
我会做类似的事情
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
这似乎是期望的行为
推荐阅读
- javascript - .push 与异步函数的问题
- nginx - nginx重新加载后返回旧数据
- python - 如何在 PULP 中初始化 LPVARIABLE.matrix 的值?
- javascript - 如何通过嵌套的数字键对对象进行排序?
- java - javax.email 是否支持在正文中添加电子邮件签名?
- r - 如何在 ggplot 图形条上方添加百分比?
- r - 如何在ggplot的散点图中显示中间点
- tcl - 在 Tcl 中查找列表元素之间的差异
- google-cloud-platform - 我可以创建的最大计算机引擎 VM 数量是多少?
- javascript - 在 Node 中强制进行垃圾回收以测试 WeakRef 和 FinalizationRegistry