lookingFor = 1
i = 0
index = 0
try:
while i < len(testlist):
index = testlist.index(lookingFor,i)
i = index + 1
print index
except ValueError: #testlist.index() cannot find lookingFor
pass
>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]
更新:
好吧,你想要一个生成器表达式,我们会有一个生成器表达式。下面是一个 for 循环中的列表内涵:
>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
... print i
...
0
5
7
现在我们要建造一个发电机。
>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
... print i
...
0
5
7
巧妙的是,我们可以把它赋给一个变量,然后从那里开始使用它..。
>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
...
0
5
7