0

我正在学习 python,但无法理解下面代码片段中的标志是怎么回事。由于我已在 if 套件中将标志更新为 false,因此我希望看到从 else 打印的 false,但输出显示为 true。有人可以帮我理解这里发生了什么。

objects=[1,2,3,4,5]
found_obj = None
for obj in objects:
    flag = True
    if obj == 3:
        found_obj = obj
        print("found the required object ",found_obj)
        flag= False

else:
    print ('Status flag ::', flag)

以下是执行此代码时得到的输出

found the required object  3
Status flag :: True
4

3 回答 3

4

但是如果我从循环中中断,我将不会进入 else。

虽然这是真的,但没有理由实际拥有一个for..else构造。由于您正在搜索列表中的元素,因此尽早退出循环是有意义的。因此,无论循环如何结束,您都应该完全删除else并运行它。print

此外,由于您尝试设置标志,无论是否找到该元素,您不应该在每次迭代时重置它:

found_obj = None
flag = True
for obj in objects:
    if obj == 3:
        found_obj = obj
        print("found the required object ",found_obj)
        flag = False
        break

print ('Status flag ::', flag)

最后,由于您是found_obj在找到元素时设置的,因此您实际上根本不需要该标志,因为值None会告诉您没有找到任何东西,而任何其他值都会告诉您确实找到了它:

found_obj = None
for obj in objects:
    if obj == 3:
        found_obj = obj
        print("found the required object ",found_obj)
        break

print ('Status flag ::', found_obj is None)
于 2015-01-04T16:39:41.440 回答
3

flag = True在每次迭代开始时设置,因此它会打印true在最后一次迭代中分配给它的位置true,其中 obj 等于 5

flag = True您可能想通过从 for 循环中移出来纠正它:

flag = True
for obj in objects:
    if obj == 3:
        found_obj = obj
        print("found the required object ",found_obj)
        flag= False
        break  # no need to continue search
于 2015-01-04T16:33:28.697 回答
0

如果break-ing 不是一个选项,这是固定代码:

objects=[1,2,3,4,5]
found_obj = None
flag = True # flag is set once, before the loop
for obj in objects:
    # this sets the flag to True *on each iteration*, we only want it once!
    # flag = True 
    if obj == 3:
        found_obj = obj
        print("found the required object ",found_obj)
        flag= False
else:
    print ('Status flag ::', flag)

这是我所知道的名为witness的循环结构的一个轻微变体,因为您只对对象列表中的单个“见证人”感兴趣3。一旦你找到了这个见证人(这是元素 3)。

于 2015-01-04T16:33:37.170 回答