gpt4 book ai didi

python - 在 Python 中的列表中查找非零数的第一个实例

转载 作者:IT老高 更新时间:2023-10-28 22:16:31 25 4
gpt4 key购买 nike

我有一个这样的列表:

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

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

myList.index(2.0)

在本例中有效,但有时第一个非零数字是 1 或 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 - 在 Python 中的列表中查找非零数的第一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19502378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com