Python 2.7x 生成器返回 bool 列表中 "False"的索引

标签 python python-2.7 generator

我正在尝试编写一个函数来返回任意列表中“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/

相关文章:

node.js - NodeJS在普通函数内调用生成器函数

python - 运行 Scrapy 但出现错误 : No module named _util

python-2.7 - 如何在 python 列表中追加行?

Python如何将方法的结果转换为生成器

python - 在Python中获取列表中每个元组的第一个元素

python - 带 (**) 的 return 语句的目的是什么

python - 链接 Python 生成器以遍历嵌套数据结构;最佳实践

python - 'local[n]' pyspark 应用程序是否受 GIL 影响?

python - 如何处理几何回归模型目标函数 exp 中的运行时溢出?

python - Vim 缩进(Python 编程)