Skip to main content
 首页 » 编程设计

python之为什么 Python 脚本会跳过某些条目而不跳过其他条目

2025年05月04日12lyj

在 Python 列表中,我希望删除的条目保留了下来,而另一个条目被删除了。这是为什么?

这是有问题的代码:

def getAdjacent(pos, bounds): 
    posibles = [ 
    [pos[0]-1, pos[1]], 
    [pos[0]+1, pos[1]], 
    [pos[0], pos[1]-1], 
    [pos[0], pos[1]+1]] 
    for p in posibles: 
        if isOutside(p,bounds): 
            posibles.remove(p) 
    return posibles 
 
 
def isOutside(pos, bounds): 
    if pos[0] > bounds[0]-1 or pos[0] < 0 or pos[1] < 0 or pos[1] > bounds[1]-1: 
        return True 
    else: 
        return False 

这里有一些反射(reflect)问题的输入和输出:

In [13]: bounds = [10, 10] 
 
In [14]: p = [9,0] 
 
In [15]: getAdjacent(p, bounds) 
Out[15]: [[8, 0], [9, -1], [9, 1]] 
 
In [16]: isOutside([9, -1], bounds) 
Out[16]: True 
 
In [17]: isOutside([9, 1], bounds) 
Out[17]: False 

现在,当 getAdjacent() 删除了所有导致 isOutside() 重新运行 True 的元素时,为什么 [9, -1] 仍在 getAdjacent() 中?为什么 [10, 0] 不在里面?这是一个重要的事情吗?

请您参考如下方法:

不要从您正在迭代的列表中删除元素:

for p in posibles: 
    if isOutside(p,bounds): 
        posibles.remove(p) 

这会混淆迭代并导致跳过条目。我会这样写

possibles = [p for p in possibles if not isOutside(p, bounds)]