![](/img/trans.png)
[英]after giving a condition for my loop to stop it continues. the print statement works, but the code continues running
[英]Program continues through the loop after a break statement
我是 python 的新手,我正在经历一些问题来练习。 问题是:
#Given an array, return the first recurring character
#Example1 : array = [2,1,4,2,6,5,1,4]
#It should return 2
#Example 2 : array = [2,6,4,6,1,3,8,1,2]
#It should return 6
lsts = [2,5,1,2,3,5,1,2,4]
def findDouble(arrs):
repeats = dict()
for arr in arrs:
repeats[arr] = repeats.get(arr, 0) + 1
if repeats[arr] == 2: break
print(arr)
findDouble(lsts)
#0(n)
我的理解是,在“中断”之后它应该结束循环,所以我应该得到 2。相反,它贯穿整个事情,我得到 2、5 和 1。我没有得到什么?
也许是更容易理解,如果你把一个print(repeats)
分配后立即repeats[arr] = ...
迭代 1:arr == 2
{2: 1} # key `2` was created and assigned `0 + 1`
迭代 2:arr == 5
{2: 1, 5: 1} # key `5` created and assigned `0 + 1`
迭代 3:arr == 1
{2: 1, 5: 1, 1: 1} # key `1` created and assigned `0 + 1`
迭代 4:arr == 2
{2: 2, 5: 1, 1: 1} # key `2` was already present, assigned `1 + 1`
repeat[arr] == 2: # evaluates to True, so it breaks
第一次循环时, arrs
为 2。该键在字典中尚不存在,因此用值 1 创建repeats[2]
,程序打印2
。
第二次循环时, arrs
为 5。该键在字典中尚不存在,因此创建了值为 1 的repeats[5]
,并且程序打印了5
。
第三次循环时, arrs
为 1。该键在字典中尚不存在,因此用值 1 创建repeats[1]
,程序打印1
。
循环第四次, arrs
为 2。该键已存在于字典中,值为 1,因此为repeats[2]
分配新值 2,循环中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.