我正在尝试编写一个函数来返回任意列表中“False”值的索引。我也想为此使用生成器。
我在下面写道:
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(x)
的文档,它返回第一个值为x
的项目的索引。这解释了为什么你的生成器总是产生 1
。
相反,您可以使用 enumerate()
像这样:
def cursor(booleanList):
for index, element in enumerate(booleanList):
if element is False:
yield index
关于Python 2.7x 生成器返回 bool 列表中 "False"的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36804901/