我对 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 areNone
.
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/