为什么Python脚本跳过某些条目而不是其他条目?

时间:2012-05-18 14:19:13

标签: python

在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

以下是一些反映问题的输入和输出:

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]仍在那里?这是一件大事吗?

1 个答案:

答案 0 :(得分:8)

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

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

这会混淆迭代并导致跳过的条目。我把它写成

possibles = [p for p in possibles if not isOutside(p, bounds)]
相关问题