python builtin enumerate returns a tuple of the index and the element. You just need to iterate over the enumerated tuple and filter only those elements which matches the search criteria
>>> mylist = ['0', '0', '1', '1', '0']
>>> [i for i,e in enumerate(mylist) if e == '1']
[2, 3]
Now coming back to your code. There are three issues that you need to understand
- Python list method index returns the position of the first occurrence of the needle in the hay. So searching '1' in mylist would always return 2. You need to cache the previous index and use it for subsequent search
- Your indentation is incorrect and your print should be inside the
if
block
Your use of is
is incorrect. is
doesn't check for equality but just verifies if both the elements have the same reference. Though in this case it will work but its better to avoid.
>>> index = 0
>>> for item in mylist:
if item == '1':
index = mylist.index(item, index + 1)
print index
2
3
Finally why worry about using index when you have enumerate.
>>> for index, item in enumerate(mylist):
if item == '1':
print index
2
3
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…