【发布时间】:2020-11-02 17:15:19
【问题描述】:
我正在编写一个函数来根据所选单元格的坐标获取正交坐标中某个单元格的邻居的坐标。我的代码是:
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)
返回:
[(-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)]
虽然它应该返回:
[(-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 删除了至少一个条件为真的所有情况,而它必须只删除两个条件都为真的情况。
我的代码有什么问题?
附:如果我将and 替换为or,代码将返回所需的输出。
在 Windows 10 上使用 Python 3.9。
【问题讨论】:
-
我认为
neigbouts是一个错字。 -
@B.Morris 当然
-
and意味着它只包括两个条件都是True的元素。 -
为了让自己更容易理解。将逻辑单独应用于您希望出现但没有出现的每个案例。例如,
0, 0的参数。您希望它包含-1, 0。如果-1不等于0并且0不等于0,您的条件就是将其包含在您的列表中。
标签: python-3.x logic boolean-logic