return first non NaN value in python list
问题 What would be the best way to return the first non nan value from this list? testList = [nan, nan, 5.5, 5.0, 5.0, 5.5, 6.0, 6.5] edit: nan is a float 回答1: If you're doing it a lot, put it into a function to make it readable and easy: import math t = [float('nan'), float('nan'), 5.5, 5.0, 5.0, 5.5, 6.0, 6.5] def firstNonNan(listfloats): for item in listfloats: if math.isnan(item) == False: return item firstNonNan(t) 5.5 回答2: You can use next, a generator expression, and math.isnan: >>> from