返回python列表中最后一个非空、非空和非空值



如何从列表中返回最后一个非空,非空和非nan ?如果不存在,则返回"null"或者定制消息!

我试过这些代码,没有一个是防弹的:

import numpy as np
listF=[0.0,np. NaN,2,0,0.0,""]
print([j for j in listF if j][-1])#returns 2 while should retrun 0
listF=[0.0,np. NaN,np. NaN,0,0.0,np. NaN]
print([j for j in listF if j][-1])#returns nan while should return 0

listF=[]
print([j for j in listF if j][-1])#returns Index out of range

listF=[1,np. NaN,np. NaN,0,0.0,np. NaN]
print([j for j in listF if j][-1])#returns nan while should return 0 
listF=[np. NaN,np. NaN,np. NaN]
print([j for j in listF if j][-1])#returns nan while should return "null"

可以通过math.isnan(或numpy.isnan)查看NA状态。将它与生成器和带有默认值的next结合使用,以处理没有有效值的情况:

from math import isnan
def last_valid(lst):
return next((x for x in reversed(lst) if x and not isnan(x)), None) # or 'null'
last_valid([])
# None
last_valid([0.0,np. NaN,2,0,0.0,""])
# 2
last_valid([1,np. NaN,np. NaN,0,0.0,np. NaN])
# 1
last_valid([0.0,np. NaN,np. NaN,0,0.0,np. NaN])
# None

接受0为有效:

给定您对规则的更新(0最初被描述为无效),您可以在第一个测试中将其转换为字符串以考虑0有效:

from math import isnan
def last_valid(lst):
return next((x for x in reversed(lst) if str(x) and not isnan(x)), '"null"')
last_valid([]))
# '"null"'
last_valid([0.0,np. NaN,2,0,0.0,""])
# 0.0
last_valid([1,np. NaN,np. NaN,0,0.0,np. NaN])
# 0.0
last_valid([0.0,np. NaN,np. NaN,0,0.0,np. NaN])
# 0.0
last_valid([np. NaN,np. NaN,np. NaN])
# '"null"'
import numpy as np
import pandas as pd
listF=[0.0,np. NaN,2,0,0.0,""]
output = 'empty list'
for tmp in listF[::-1]:
if not tmp or pd.isna(tmp):
continue
else:
output = tmp
break
output

这是你几乎得到的在线演讲者。您必须记住,在布尔表达式中nan不是假的!但如果与自身比较,总是返回false:)

print([i for i in list if i and not i!=i][-1])

最新更新