【问题标题】:How do I deal with an edge case when replacing None values in a list?替换列表中的 None 值时如何处理边缘情况?
【发布时间】:2020-09-15 00:09:09
【问题描述】:

我希望用前面的值替换列表中的 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)

【问题讨论】:

  • 列表中的预期输出是什么:[None, None, 1]?

标签: python arrays nonetype


【解决方案1】:

我会做类似的事情

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

这似乎是期望的行为

【讨论】:

    【解决方案2】:

    如果您想使用性能更快的简约代码,我提出了以下使用 Pandas 库的解决方案,这在这种情况下可能很有用:

    import pandas as pd
    
    def replaceNone(myList):
        myList = pd.DataFrame(myList)
        return myList.fillna(method='ffill').values.flatten().tolist()
    
    myList = [None,1,2,2,None,None,3]
    replaceNone(myList)
    

    【讨论】:

      猜你喜欢
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多