python2.7x生成器返回布尔lis中“False”的索引

2024-04-19 02:58:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

代码中的问题在哪里?任何帮助都将不胜感激。你知道吗


Tags: 代码infalsetruemostelementcallcursor
3条回答

查看^{}的文档,它返回值为x的第一项的索引。这解释了为什么生成器总是产生1。你知道吗

相反,您可以这样使用^{}

def cursor(booleanList):
  for index, element in enumerate(booleanList):
    if element is False:
      yield index

这是您的索引列表[0:True, 1:False, 2:True, 3:False]现在booleanList.index搜索列表中的第一个False,并返回当然总是1的索引。你知道吗

你错误地认为for element in booleanList:以某种方式耗尽了booleanList,但事实并非如此。你知道吗

您需要改用rangedfor

def cursor(booleanList):
  for index in range(0, len(booleanList):
    if booleanList[index] is False:
      yield index


testList = [True, False, True, False]

g = cursor(testList)

print g.next()
print g.next()
print g.next()

作为前面答案的扩展,您还可以使用generator expression。诚然,这是一个更为定制的解决方案,但可能适用于您的用例。只是出于好奇,如果你的记忆中已经有了列表,为什么要使用生成器呢?你知道吗

testList = [True, False, True, False]

g = (i for i in range(len(testList)) if testList[i] is False)

for i in g:
    print i

相关问题 更多 >