2014-03-02 47 views
1

返回第一個非NaN的值會是什麼,從這個列表返回第一個非NaN值的最佳方式?在Python列表

testList = [nan, nan, 5.5, 5.0, 5.0, 5.5, 6.0, 6.5] 

編輯:

楠是一個浮動

+1

什麼是'這裏nan'? – thefourtheye

回答

2

如果你做了很多,把它進入功能,使其易讀易:

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 
5

您可以使用next,一個generator expression,並math.isnan

>>> from math import isnan 
>>> testList = [float('nan'), float('nan'), 5.5, 5.0, 5.0, 5.5, 6.0, 6.5] 
>>> next(x for x in testList if not isnan(x)) 
5.5 
>>> 
+0

'下一個(X爲testList X如果x == X)'會工作過了,它可能是一個有點快,因爲它避免了功能的大量查詢的(雖然相當不可讀)。 – Bakuriu