【问题标题】:How to stop look returning None when there is an element that satisfies if condition?当有一个满足 if 条件的元素时,如何停止返回 None?
【发布时间】:2019-04-22 14:06:03
【问题描述】:

我正在循环一个布尔值列表 我的条件是元素的位置是否 > m 和if the element = True

函数会返回元素的位置

这就是我所做的:

panda =[True, True, True, True]

def find_next (l, m): 
    for i in l:  
        if ((l.index(i) > m) and i ==True):
            return l.index(i) 

print(find_next(panda, 2))

我预计输出为 3。

但我得到了None。为什么?

【问题讨论】:

  • 欢迎来到 Stack Overflow。该代码将生成一个IndentationError。请edit您的问题并解决它。我们不能指望猜测哪些错误是相关的,哪些不相关。最简单的做法是粘贴您的代码,然后选择它并单击 {} 按钮或按 Ctrl+K。

标签: python loops boolean


【解决方案1】:

l.index(i) 总是返回 0,因为它会在您的列表中找到 True 的第一个实例

顺便说一句,您不需要在每个循环上都调用 l.index,因为当您应该已经知道自己正在进行的迭代时,您正在冗余地搜索列表。

def find_next(l, m):
    for index, value in enumerate(l):
        if index > m and value:
            return index

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多