40

我有一个这样的列表:

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

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

myList.index(2.0)

它在本例中有效,但有时第一个非零数是 1 或 3。

有没有一种快速的方法来做到这一点?

4

9 回答 9

60

next与 一起使用enumerate

>>> 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
于 2013-10-21T18:54:03.620 回答
20

使用过滤器

蟒蛇2:

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

myList.index(filter(lambda x: x!=0, myList)[0])       # 3
myList2.index(filter(lambda x: x!=0, myList2)[0])     # IndexError

Python 3:(感谢 Matthias 的评论):

myList.index(next(filter(lambda x: x!=0, myList)))    # 3
myList2.index(next(filter(lambda x: x!=0, myList2)))  # StopIteration
# from Ashwini Chaudhary's answer
next((i for i, x in enumerate(myList) if x), None)    # 3
next((i for i, x in enumerate(myList2) if x), None)   # None

你必须处理特殊情况。

于 2013-10-21T19:08:08.953 回答
7

您可以使用numpy.nonzero

myList = [0.0, 0.0, 0.0, 2.0, 2.0]
I = np.nonzero(myList)
# The first index is necessary because the vector is within a tuple
first_non_zero_index = I[0][0]
# 3
于 2016-01-16T10:33:18.300 回答
6

这是一个单一的班轮做到这一点:

val = next((index for index,value in enumerate(myList) if value != 0), None)

基本上,它使用next()来查找第一个值,None如果没有则返回。enumerate()用于创建迭代索引、值元组的迭代器,以便我们知道我们所在的索引。

于 2013-10-21T19:00:30.920 回答
4

用这个:

[i for i, x in enumerate(myList) if x][0]
于 2017-06-20T14:17:42.503 回答
3

当数组很大时,使用nextwith非常好。enumerate对于较小的数组,我会使用argmaxNumPy,这样您就不需要循环:

import numpy as np

myList = [0.0, 0.0, 0.0, 2.0, 2.0]
myArray = np.array(myList)
np.argmax(myArray > 0)
3
于 2017-03-07T18:21:09.840 回答
1

那么使用枚举呢?检查枚举文档。

def first_non_zero(mylist):
  for index, number in enumerate(mylist):
    if number != 0: # or 'if number:'
      return index
于 2013-10-21T18:55:47.643 回答
1

请执行下列操作:

print (np.nonzero(np.array(myList))[0][0])

这更方便,因为除了查找非零值外,这还有助于直接应用逻辑函数。例如:

print (np.nonzero(np.array(myList)>1))
于 2018-09-14T09:55:45.327 回答
0

只需使用列表推导:

myDict = {x: index for index, x in enumerate(myList) if x}

非零元素的索引是myDict[element]

于 2013-10-21T18:55:43.700 回答