我有这样的清单
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
使用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
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)
小智 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)
这是一个单行班轮:
val = next((index for index,value in enumerate(myList) if value != 0), None)
Run Code Online (Sandbox Code Playgroud)
基本上,它使用next()来查找第一个值,None
如果没有则返回.enumerate()用于创建迭代器,迭代索引,值元组,以便我们知道我们所处的索引.
归档时间: |
|
查看次数: |
31920 次 |
最近记录: |