【发布时间】:2016-04-22 23:44:58
【问题描述】:
我正在尝试编写一个函数来返回任意列表中“假”值的索引。我也想为此使用生成器。
我写在下面:
def cursor(booleanList):
for element in booleanList:
if element is False:
yield booleanList.index(element)
例如,我有下面的列表
testList = [True, False, True, False]
然后:
g = cursor(testList)
但是,如果我使用我的代码,我会得到:
> g.next()
1
> g.next()
1
> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
而我希望得到:
> g.next()
1
> g.next()
3
> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
代码中的问题在哪里?任何帮助将不胜感激。
【问题讨论】:
-
如果你想使用
index,尤其是在循环中,你真正需要的可能是enumerate。 -
[ind for ind, value in enumerate(testList) if not value]
标签: python python-2.7 generator