【问题标题】:Python 3 : why my "and" functions as "or" in "if" conditionsPython 3:为什么我的“and”在“if”条件下充当“or”
【发布时间】: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


【解决方案1】:

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

也就是说,你想要:

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

等同于:

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

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

【讨论】:

  • 我可以理解,为什么not (temp_x == x and temp_y == y) 是我需要的。但是,你能解释为什么它是一样的吗?据我了解,代码if (temp_x != x) or (temp_y != y) 应该完全放下中心线和列
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多