Python在列表中找到非零数字的第一个实例

use*_*196 30 python list

我有这样的清单

myList = [0.0 , 0.0, 0.0, 2.0, 2.0]
Run Code Online (Sandbox Code Playgroud)

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

myList.index(2.0)
Run Code Online (Sandbox Code Playgroud)

适用于此示例,但有时第一个非零数字将为1或3.

有这么快的方法吗?

Ash*_*ary 48

使用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
Run Code Online (Sandbox Code Playgroud)


Puf*_*GDI 16

使用过滤器

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
Run Code Online (Sandbox Code Playgroud)

  • 对于python 3你可以使用`myList.index(next(filter(lambda x:x!= 0,myList))) (3认同)
  • 另一个很好的选择,与`next`的主要区别在于`next`提供了一个默认值,而这会引发异常. (2认同)

小智 6

您可以使用 numpy.nonzero:http ://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.nonzero.html

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
Run Code Online (Sandbox Code Playgroud)


Mur*_*rph 5

这是一个单行班轮:

val = next((index for index,value in enumerate(myList) if value != 0), None)
Run Code Online (Sandbox Code Playgroud)

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


Seb*_*bMa 5

用这个:

[i for i, x in enumerate(myList) if x][0]
Run Code Online (Sandbox Code Playgroud)