Skip to main content
 首页 » 编程设计

python之为什么此代码会返回列表索引错误

2025年05月04日11jackei

基本上它应该获取一组坐标并返回它的邻居的坐标列表。然而,当它到达这里时:

if result[i][0] < 0 or result[i][0] >= board.dimensions: 
    result.pop(i) 

当 i 为 2 时,它会给我一个超出索引的错误。我可以设法让它打印 result[2][0] 但在 if 语句中它会抛出错误。为什么会这样?

def neighborGen(row,col,board): 
    """ 
    returns lists of coords of neighbors, in order of up, down, left, right 
    """ 
 
    result = [] 
    result.append([row-1 , col]) 
    result.append([row+1 , col]) 
    result.append([row , col-1]) 
    result.append([row , col+1]) 
 
     #prune off invalid neighbors (such as (0,-1), etc etc) 
     for i in range(len(result)):  
        if result[i][0] < 0 or result[i][0] >= board.dimensions: 
            result.pop(i) 
        if result[i][1] < 0 or result[i][1] >= board.dimensions: 
            result.pop(i) 
 
    return result  

请您参考如下方法:

您从列表中获取要迭代的索引,然后继续从列表中删除元素。最终你会遇到一个不再存在的索引。改用列表理解来过滤。

result = [entry for entry in result if entry[0] >= 0 and 
  entry[0] < board.dimensions and entry[1] >= 0 and 
  entry[1] < board.dimensions]