【发布时间】:2018-11-16 20:15:50
【问题描述】:
我对 np.where() 函数感到困扰。 (在我的示例中为第 7 行)
背景:我正在编写游戏“Connect Four”。这个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
【问题讨论】:
-
is检查col_entries(所以你的矩阵本身)是否为None。所以这是总是False. -
This site 是检查python中
is和==之间区别的好地方。 -
比较
(col_entries is None)和(col_entries==None)。测试先完成,然后传递给where。如果测试数组没有意义,那么where结果也不会。 -
无总是需要检查
is。其他任何东西都不安全。 -
dtype的self.board是什么?object还是数字?具有数字 dtype 的数学更快,但它不能容纳None对象。而object dtype数组更像是一个列表,或者如果是2d,则是一个列表的列表。