2017-05-09 36 views
-2

這裏是我的代碼,其中我試圖在創建元組映射列表時嘗試引用元組的牆列表,其中索引[variable] [2]作爲牆或樓層的屬性:'break'關鍵字是否阻止代碼在Python中再次運行該循環?

map = [] 
walls = [(0,3), (0,4), (0,5), (0,7), (2,7), (3,7), (4,7), (5,7), (1,7), 
(5,6), (5,4), (2,3), (2,4), (3,5), (3,0), (3,1), (3,2), (7,0), (7,1), (7,5), 
(7,6), (7,7), (8,7)] 
for x in range(9): 
    for y in range(9): 
     for a in range(len(walls)): 
      if walls[a][0] == x and walls[a][1] == y: 
       map.append(tuple((x,y,"w"))) 
      else: 
       map.append(tuple((x,y,"_"))) 
      break 

---> [(0, 0, '_'), (0, 1, '_'), (0, 2, '_'), (0, 3, 'w'), (0, 4, '_'), (0, 5, '_'), (0, 6, '_'), (0, 7, '_'), (0, 8, '_'), (1, 0, '_'), (1, 1, '_'), (1, 2, '_'), (1, 3, '_'), (1, 4, '_'), (1, 5, '_'), (1, 6, '_'), (1, 7, '_'), (1, 8, '_'), (2, 0, '_'), (2, 1, '_'), (2, 2, '_'), (2, 3, '_'), (2, 4, '_'), (2, 5, '_'), (2, 6, '_'), (2, 7, '_'), (2, 8, '_'), (3, 0, '_'), (3, 1, '_'), (3, 2, '_'), (3, 3, '_'), (3, 4, '_'), (3, 5, '_'), (3, 6, '_'), (3, 7, '_'), (3, 8, '_'), (4, 0, '_'), (4, 1, '_'), (4, 2, '_'), (4, 3, '_'), (4, 4, '_'), (4, 5, '_'), (4, 6, '_'), (4, 7, '_'), (4, 8, '_'), (5, 0, '_'), (5, 1, '_'), (5, 2, '_'), (5, 3, '_'), (5, 4, '_'), (5, 5, '_'), (5, 6, '_'), (5, 7, '_'), (5, 8, '_'), (6, 0, '_'), (6, 1, '_'), (6, 2, '_'), (6, 3, '_'), (6, 4, '_'), (6, 5, '_'), (6, 6, '_'), (6, 7, '_'), (6, 8, '_'), (7, 0, '_'), (7, 1, '_'), (7, 2, '_'), (7, 3, '_'), (7, 4, '_'), (7, 5, '_'), (7, 6, '_'), (7, 7, '_'), (7, 8, '_'), (8, 0, '_'), (8, 1, '_'), (8, 2, '_'), (8, 3, '_'), (8, 4, '_'), (8, 5, '_'), (8, 6, '_'), (8, 7, '_'), (8, 8, '_')] 

問題:只有一個座標被檢查和分配'w',而其餘的不是。我認爲這個問題的邏輯是斷言。 break語句是否會阻止最後一個嵌套for循環再次運行。如果不行:x = 0,y = 3,a = 0,break ---> x = 0,y = 4,a = 0,a = 1,break ---> ...

+3

你覺得'break'有什麼用? –

+3

'break'突破當前循環。它不會阻止循環再次運行(如果它在另一個循環中)。但是你最內層的循環總是會在第一次迭代中斷開,因爲你的'break'不在'if'語句中。 – khelwood

+0

如果break語句在if語句內,它也是一樣的。 – TB2

回答

0

來自python文檔:

break語句,就像在C中,打破了最小的封閉for或while循環。

進一步閱讀here

希望這會幫助你,Yahli。

相關問題