python - np.where(condition is None) 不等于 np.where(condition == None)

标签 python numpy

我对 np.where() 函数感到困扰。 (在我的示例中为第 7 行)

背景:我正在编写游戏“连连四”。此 insert_chip() 方法访问变量 self.board,它是我个人数据类型 Chip 的 8x8 np 数组。如果self.board的条目中没有chip,则值为None

出于某种原因,np.where(col_entries is None) 不返回None 元素的索引。当我在条件中写入 col_entries == None 时,为什么会收到不同的输出?这不是如果 None 有引用权吗?

def insert_chip(self, chip, col):
    # slices the entries of the column into a new array
    col_entries = self.board[:, col:col+1]

    # checks for all unoccupied pos in this col (entries are None)
    # gives double array of indexes with the form (array([row_i, ...]), array([col_i, ...]))
    none_indexes = np.where(col_entries is None)

    # the pos where the chip will fall is the one with the highest index
    self.board[len(none_indexes[0]), col] = chip

最佳答案

For some reason, np.where(col_entries is None) does not return the indices of the elements that are None.

is运算符检查两个操作数是否指向同一个对象。所以在这里它检查是否 col_entries (矩阵)是 None ,因此它执行“广播”以检查矩阵中的某些元素是否引用 None .

在 Python 中,可以重载某些运算符,例如 <= , ==等。Numpy 利用它来实现特定的运算符,这样就可以编写 some_matrix == 0生成 bool 矩阵。 is运算符不能被重载,因此 Numpy(或任何其他库)可以控制它。 is简单地检查两个操作数是否引用同一个对象。

因为这里是您的 col_entries引用一个 numpy 数组,这将始终是 False ,因此 np.where(col_entries is None)将始终返回一个包含空数组的 1 元组。

虽然没有那么多对象等于None ,指望它仍然不是很安全。我们可以向量化 is运算符,例如:

from operator import is_

np.where(np.vectorize(is_)(col_entries, None))

关于python - np.where(condition is None) 不等于 np.where(condition == None),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53344789/

相关文章:

Python - Tweepy - 列表引用问题

通过 Jenkins 实现 Python Excel 自动化

python - 制作一个可以接受各种形状参数的函数

python - Pandas 删除所有包含任何 nan 的列,除了一个

python - 在不使用 for 循环的情况下删除 numpy 数组的前导零

python - Python 读取和写入 csv 文件

python - 将没有主键的 CSV 导入现有表

python - 初始化数据类中字段的默认值时调用方法

python - Karush–Kuhn–Tucker (KKT) 条件和 SciPy

python - 如何获取 numpy 二维数组中列的排名?