簡體   English   中英

“for”循環如何工作python?

[英]how does "for" loop works python?

為什么會發生,在四次 while 迭代中“for 循環”僅迭代 2 次,而數組長度為 3

import time
array = [[1, 1, 3], [2, 2, 3], [3, 3, 3]]

while True:
    #print (array)
    time.sleep(1)
    index = 0
    print (array)
    for proxy in array:
        
        print("iteration")
        if proxy[2] == 0:
            del array[index]
            continue
        
        proxy[2] -= 1
        index += 1
    print ("\n")

編譯

當任何數組的最后一項變為 0 時(在幾圈后發生),您就刪除了該項。 這使得只有 2 個項目而不是 3 個,並且 for 循環遍歷這些項目,因此它只迭代兩次。

編輯::一個好的解決方案是制作數組的副本,以便您可以使用一個來刪除項目,並使用一個來迭代(循環)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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