Python 3 : 为什么我的 "and" 在 "if" 条件下发挥着 "or" 的作用

Python 3 : why my "and" functions as "or" in "if" conditions

我正在编写一个函数,以根据所选单元格的坐标获取正交坐标中特定单元格的邻居坐标。我的代码是:

def get_neighbours_coordinates (x, y):
    neighbours = []
    for temp_x in [x-1, x, x+1]:
        # condition to drop the case, when cell has the same coordinates as treated
        for temp_y in [y-1, y, y+1]:
            if (temp_x != x) and (temp_y != y):
                neighbours.append((temp_x, temp_y))
    print (neighbours)

然后,如果我将其称为(例如):

for i in range (10):
    get_neighbours_coordinates(i, i)

它returns:

[(-1, -1), (-1, 1), (1, -1), (1, 1)]
[(0, 0), (0, 2), (2, 0), (2, 2)]
[(1, 1), (1, 3), (3, 1), (3, 3)]
[(2, 2), (2, 4), (4, 2), (4, 4)]
[(3, 3), (3, 5), (5, 3), (5, 5)]
[(4, 4), (4, 6), (6, 4), (6, 6)]
[(5, 5), (5, 7), (7, 5), (7, 7)]
[(6, 6), (6, 8), (8, 6), (8, 8)]
[(7, 7), (7, 9), (9, 7), (9, 9)]
[(8, 8), (8, 10), (10, 8), (10, 10)]

虽然它应该 return:

[(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2)]
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (3, 3)]
[(2, 2), (2, 3), (2, 4), (3, 2), (3, 4), (4, 2), (4, 3), (4, 4)]
[(3, 3), (3, 4), (3, 5), (4, 3), (4, 5), (5, 3), (5, 4), (5, 5)]
[(4, 4), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), (6, 5), (6, 6)]
[(5, 5), (5, 6), (5, 7), (6, 5), (6, 7), (7, 5), (7, 6), (7, 7)]
[(6, 6), (6, 7), (6, 8), (7, 6), (7, 8), (8, 6), (8, 7), (8, 8)]
[(7, 7), (7, 8), (7, 9), (8, 7), (8, 9), (9, 7), (9, 8), (9, 9)]
[(8, 8), (8, 9), (8, 10), (9, 8), (9, 10), (10, 8), (10, 9), (10, 10)]

看起来 and 删除了至少一个条件为真的所有情况,而它必须只删除两个条件都为真的情况。

我的代码有什么问题?

P.S。如果我将 and 替换为 or,代码 return 就是所需的输出。
在 Windows 10.

上使用 Python 3.9

您看到的结果与您的布尔逻辑一致。通过说 and 你是说你想 排除 有问题的单元格的整个行和列。您真正想要排除的唯一单元格是查询单元格本身。

即你想要:

not (temp_x == x and temp_y == y)

等同于:

(temp_x != x) or (temp_y != y)

这个逻辑等价是 De Morgan's Laws 之一。