簡體   English   中英

程序在 break 語句后繼續循環

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM