返回 python 列表中的第一个非 NaN 值 [英] return first non NaN value in python list

查看:96
本文介绍了返回 python 列表中的第一个非 NaN 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从该列表中返回第一个非 nan 值的最佳方法是什么?

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]

nan 是一个浮点数

nan is a float

推荐答案

如果你经常做这件事,把它放到一个函数中,使其可读性更强:

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

这篇关于返回 python 列表中的第一个非 NaN 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆