问题
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