Python在列表中找到非零数字的第一个实例 [英] Python find first instance of non zero number in list

查看:1589
本文介绍了Python在列表中找到非零数字的第一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表

myList = [0.0 , 0.0, 0.0, 2.0, 2.0]

我想找到列表中第一个不等于零的数字的位置.

I would like to find the location of the first number in the list that is not equal to zero.

myList.index(2.0)

在此示例中有效,但有时第一个非零数字将为1或3.

Works in this example but sometimes the first non zero number will be 1 or 3.

有快速的方法吗?

推荐答案

nextenumerate一起使用:

>>> myList = [0.0 , 0.0, 0.0, 2.0, 2.0]
>>> next((i for i, x in enumerate(myList) if x), None) # x!= 0 for strict match
3

这篇关于Python在列表中找到非零数字的第一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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