简体   繁体   English

程序在 break 语句后继续循环

[英]Program continues through the loop after a break statement

I'm new to python and I was going through a few problem to practice.我是 python 的新手,我正在经历一些问题来练习。 The question is:问题是:

#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)

My understanding is that after the "break" it should end the loop, so I should just get 2. Instead it goes through the entire thing and I get 2, 5, and 1. What am I not getting?我的理解是,在“中断”之后它应该结束循环,所以我应该得到 2。相反,它贯穿整个事情,我得到 2、5 和 1。我没有得到什么?

Perhaps it is easier to understand if you put a print(repeats) right after assigning repeats[arr] = ...也许是更容易理解,如果你把一个print(repeats)分配后立即repeats[arr] = ...

Iteration 1: arr == 2迭代 1:arr == 2

{2: 1} # key `2` was created and assigned `0 + 1`

Iteration 2: arr == 5迭代 2:arr == 5

{2: 1, 5: 1} # key `5` created and assigned  `0 + 1`

Iteration 3: arr == 1迭代 3:arr == 1

{2: 1, 5: 1, 1: 1} # key `1` created and assigned `0 + 1`

Iteration 4: arr == 2迭代 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

The first time through the loop, arrs is 2. That key does not yet exist in the dictionary, so repeats[2] is created with a value of 1, and the program prints 2 .第一次循环时, arrs为 2。该键在字典中尚不存在,因此用值 1 创建repeats[2] ,程序打印2

The second time through the loop, arrs is 5. That key does not yet exist in the dictionary, so repeats[5] is created with a value of 1, and the program prints 5 .第二次循环时, arrs为 5。该键在字典中尚不存在,因此创建了值为 1 的repeats[5] ,并且程序打印了5

The third time through the loop, arrs is 1. That key does not yet exist in the dictionary, so repeats[1] is created with a value of 1, and the program prints 1 .第三次循环时, arrs为 1。该键在字典中尚不存在,因此用值 1 创建repeats[1] ,程序打印1

The fourth time through the loop, arrs is 2. That key already exists in the dictionary with a value of 1, so repeats[2] is assigned a new value of 2, and the loop breaks.循环第四次, arrs为 2。该键已存在于字典中,值为 1,因此为repeats[2]分配新值 2,循环中断。

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

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