Python,但不是编程,新手在这里。我正在使用列表进行编程并且遇到了一个有趣的问题。
width = 2
height = 2
# Traverse the board
def traverse(x, y):
# The four possible directions
squares = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
print squares
# Remove impossible squares
for square in squares:
print "now accessing", square
if (square[0] < 1 or square[0] > width or
square[1] < 1 or square[1] > height or
square == (1, height)):
squares.remove(square)
print "removed", square
print(squares)
# Testing traverse
traverse(1,1)
这将产生以下输出:
[(0, 1), (2, 1), (1, 0), (1, 2)]
now accessing (0, 1)
removed (0, 1)
now accessing (1, 0)
removed (1, 0)
[(2, 1), (1, 2)]
它完全跳过元素 (2,1) 和 (1,2) - 甚至不检查它们!我在这里找到了答案,说我不应该在遍历列表时修改它,是的,这绝对是有道理的。菜鸟失误。但是有人能告诉我为什么它不起作用吗?Python 列表的面纱背后是什么?