Python:对于循环行为很奇怪

1 python for-loop

我试图解决这个问题:CodeEval.

这个问题要求我查看XY坐标中可能的点候选列表.然后,如果它们满足要求,我将它们添加到"已确认"列表中,然后将周围的点添加到"tosearch"列表中.然而,这并不像我期望的那样表现.

示例代码:

Starting point
tosearch=[[0,0]] 

for point in tosearch:

    if conditions filled:
        confirmed.append(point)
        #Basically Im trying to add (x,y-1) etc. to the tosearct list
        tosearch.append([point[0],point[1]-1])  #1 
        tosearch.append([point[0]+1,point[1]])  #2
        tosearch.append([point[0]-1,point[1]-1])#3
        tosearch.append([point[0],point[1]+1])  #4
        tosearch.remove(point)
else:
     tosearch.remove(point)
Run Code Online (Sandbox Code Playgroud)

这似乎导致总是忽略一半的追加.因此,在这种情况下,#1和#3被忽略.如果我只留下1和2,那么只有2个会执行.我不明白......

也许问题是其他地方所以这里是整个代码: Pastebin

Mat*_*nes 5

您正在迭代它时修改集合.
2个选项:

  1. 复制列表,迭代副本,并更改​​原始.
  2. 跟踪需要进行的更改,并在迭代后完成所有更改.