Python 程序在中断语句后继续循环
我是python新手,我正在经历一些需要练习的问题。问题是:Python 程序在中断语句后继续循环,python,dictionary,break,Python,Dictionary,Break,我是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 findDoub
#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。我没有得到什么?如果您在分配
repeats[arr]=…
之后立即放置打印(repeats)
,可能更容易理解
迭代1:arr==2
{2: 1} # key `2` was created and assigned `0 + 1`
{2: 2, 5: 1, 1: 1} # key `2` was already present, assigned `1 + 1`
repeat[arr] == 2: # evaluates to True, so it breaks
迭代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: 1} # key `2` was created and assigned `0 + 1`
{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。该键在字典中还不存在,因此repeats[2]
的值为1,程序将打印2
通过循环的第二次,arrs
为5。该键在字典中还不存在,因此repeats[5]
的值为1,程序将打印5
通过循环的第三次,arrs
为1。该键在字典中还不存在,因此repeats[1]
的值为1,程序将打印1
通过循环的第四次,
arrs
为2。字典中已经存在值为1的键,因此repeats[2]
被分配一个新的值2,循环中断。循环到达第二个2
时会中断。但在此之前,它会找到2、5和1,所以它会打印它们。看起来您希望代码在整个列表中找到任何重复项,但它没有这样做——它只在它看到的列表部分中找到重复项。一旦到达重复的2
值,它就会停止。从逻辑上考虑:在什么条件下达到print(arr)
?第一次通过循环会发生什么-是否会达到print(arr)
?为什么?第二次怎么样?第三个?你真的希望这个print
语句在循环中吗?为什么?@KarlKnechtel你的暗示让我意识到了我的错误。感谢您在中断之前,将打印语句移动到if
的内部。就像现在一样,它每次通过循环都会打印。