繁体   English   中英

当有满足条件的元素时,如何停止查找返回 None ?

[英]How to stop look returning None when there is an element that satisfies if condition?

我正在遍历布尔值列表,我的条件是如果元素的位置 > 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 为什么?

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

l.index ,您不需要在每个循环上都调用l.index因为当您应该已经知道您正在进行什么迭代时,您正在冗余搜索列表。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM