我在Python中遇到了循环中断语句

问题描述 投票:0回答:1
 def findpos(l, v):
    (found, i) = (False, 0)
    while i < len(l):
        if not found and l[i] == v:
            (found, pos) = (True, i)
        if not found:
            pos = -1
        i += 1 
    return pos

#it 是查找输入值第一次出现的代码,以查找其索引。它工作得很好,但我无法理解它的工作过程。 `

python while-loop iteration
1个回答
0
投票

发现变量 = false 且 i = 0

(found, i) = (False, 0)

只要 i 就执行循环 < lenght list, it means that it runs from the beginning to the end of the list

while i < len(l)

稍后,我们检查之前没有找到它,但它在当前位置

if not found and l[i] == v:

如果这是真的,found = true 并且 i = 实际位置

(found, pos) = (True, i)

如果没有找到,pos = -1

if not found:
        pos = -1

由于还没有找到,我们在列表中一一上移

i += 1 

最后返回pos

return pos

简而言之,它会逐一检查“l”中是否找到元素“v”,如果找到,则循环继续执行,但始终以 pos=found_at_position_x 为条件。如果没有找到,则返回值-1。我希望它有帮助

© www.soinside.com 2019 - 2024. All rights reserved.