Indexes of first occurrences of zeroes in Python list

早过忘川 提交于 2019-12-04 02:33:34

问题


I have a list like this,

import numpy as np
myList = [0.0 , 0.0, 0.0, 2.0, 2.0, 0.0, 2.5, 0.0, 0.0, 0.0, 3.0, 0.0]

I can find the index of non zero occurrence like below.

I = np.nonzero(myList)
for i in I:
  print(i)

Can I find the index of first occurrence of zeros? something like below,

[0, 5, 7, 11]

回答1:


Since NumPy tagged, here are two ways -

In [44]: m = np.r_[False,np.equal(myList,0)]

In [45]: np.flatnonzero(m[:-1]<m[1:])
Out[45]: array([ 0,  5,  7, 11])

If the input is an array, becomes a bit easier to get the equivalent mask m -

a = np.array(myList)
m = np.r_[False,a==0]

Another way with np.diff for a one-liner -

In [46]: np.flatnonzero(np.diff(np.r_[0,np.equal(myList,0)])==1)
Out[46]: array([ 0,  5,  7, 11])

Easier again with array input a -

In [52]: np.flatnonzero(np.diff(np.r_[0,a==0])==1)
Out[52]: array([ 0,  5,  7, 11])



回答2:


With python

i = True
r = []
l = [0.0 , 0.0, 0.0, 2.0, 2.0, 0.0, 2.5, 0.0, 0.0, 0.0, 3.0, 0.0]
for a in range(len(l)):
    if l[a] == 0:
        if i:
            r.append(a)
            i = False
    else:
        i = True
print(r)

Prints

[0, 5, 7, 11]


来源:https://stackoverflow.com/questions/58890548/indexes-of-first-occurrences-of-zeroes-in-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!