【问题标题】:Python 2.7x generators to return indexes of "False"s in a Boolean listPython 2.7x 生成器在布尔列表中返回“False”的索引
【发布时间】: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


【解决方案1】:

查看.index(x)的文档,它返回值为x的第一项的索引。这就解释了为什么你的生成器总是产生1

相反,您可以像这样使用enumerate()

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

【讨论】:

  • 你应该使用if not element: yield index
  • @user3100115 我想这取决于,也许作者不希望0 被屈服。
  • 不,列表中元素的类型是bool
  • @user3100115 确实如此,但正如其名称所述,它是一个“测试”列表。我们不知道这个列表到底是什么,也不知道它是如何创建的。所以我更愿意让作者决定什么最适合它的需求。
【解决方案2】:

作为先前答案的扩展,您还可以使用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

【讨论】:

    【解决方案3】:

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

    您错误地认为for element in booleanList: 不知何故耗尽了booleanList,但事实并非如此。

    您需要改用远程for

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 2017-06-10
      • 2015-10-17
      • 1970-01-01
      • 2019-06-10
      • 2017-08-18
      • 2017-11-23
      相关资源
      最近更新 更多