簡體   English   中英

For循環不會遍歷所有對象

[英]For-loop does not go over all objects

為什么此for循環未遍歷所有項目:

 temp = 0

 for br in my_list :
    temp +=1
    #other code here
    #my list is not used at all, only br is used inside here
    my_list.remove(br)

 print temp
 assert len(my_list) == 0 , "list should be empty"

因此,斷言會觸發。 然后我添加了臨時計數器,我確實看到盡管我的列表有202個元素,但是for循環僅處理其中的101個元素。 這是為什么?

您不應該從要迭代的列表中刪除。 如果您要刪除東西,請使用它

while list:
   item = list.pop()
   #Do stuff

編輯:如果您想更多地了解pop()查看python文檔

如果順序很重要,請使用pop(0) pop()默認會刪除最后一個項目,如果要瀏覽列表,則應使用pop(0)刪除第一個(索引0)項目並返回它。

Edit2:感謝用戶Vincent提供的while list建議。

for br in my_list[:] :替換for br in my_list : for br in my_list[:] : 因此,您將遍歷源列表的副本。

tobias_k是正確的,可從要迭代的列表中刪除項目,這會導致各種問題。

在這種情況下,通過使用repl在每個循環上打印列表,可以很容易地表明它導致迭代跳過:

for br in my_list:
  my_list.remove(br)
  print my_list

這將產生:

[1, 2, 3, 4, 5]
[1, 3, 4, 5]
[1, 3, 5]

最后留下my_list包含:[1、3、5]

要執行您想要的操作,mic4ael是正確的,最簡單(盡管可能不是最有效的)方法是在遍歷列表之前先獲取列表的副本,如下所示:

my_list = [0,1,2,3,4,5]
for br in my_list[:]:     #The [:] takes a copy of my_list and iterates over it
  my_list.remove(br)
  print my_list

這將產生:

[1, 2, 3, 4, 5]
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]

如果您確實需要盡快回收列表中項目所使用的內存,則可以像這樣釋放它們

for i, br in enumerate(my_list):
    #other code here
    my_list[i] = None

除了Jython之外,Java會在感覺合適時釋放它們

暫無
暫無

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

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