Python2.7x生成器返回索引;假;布尔列表中的s
我试图编写一个函数来返回任意列表中“False”值的索引。我也想用发电机来做这个 我写道:Python2.7x生成器返回索引;假;布尔列表中的s,python,python-2.7,generator,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) 但是,如果我使用
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.下一步()
1.
>g.下一步()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
停止迭代
鉴于我希望得到:
> g.next()
1
> g.next()
3
> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>g.next()
1.
>g.下一步()
3.
>g.下一步()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
停止迭代
代码中的问题在哪里?任何帮助都将不胜感激。请查看的文档,它返回第一项的索引,该项的值为
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的索引
您错误地认为对于booleanList中的元素:
某种程度上耗尽了booleanList
,但事实并非如此
您需要为使用范围:
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()
作为前面答案的延伸,您还可以使用。诚然,这是一个更为定制的解决方案,但可能适用于您的用例。出于好奇,如果您已经在内存中存储了列表,为什么要使用生成器
testList = [True, False, True, False]
g = (i for i in range(len(testList)) if testList[i] is False)
for i in g:
print i
如果你想使用索引
,尤其是在循环中,你真正需要的可能是枚举
[ind for ind,value in enumerate(testList)If not value]
你应该使用If not元素:yield index
@user3100115我想这取决于,可能作者不希望产生0
。不,列表中的元素类型确实是bool
@user3100115,但正如其名称中所述,它是一个“测试”列表。我们不知道这个列表到底是什么,也不知道它是如何创建的。所以我更喜欢让作者决定什么最适合它的需要。