我对np.where()函数感到困扰。(我的例子中的第7行)
背景:我正在编写游戏“连接四”。这个insert_chip()方法访问变量self.board,它是个人dtype Chip的一个8x8np数组。如果在chip的条目中没有self.board,那么这个值就是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发布于 2018-11-16 20:30:03
创建一个对象dtype数组:
In [37]: arr = np.zeros((3,3), object)
In [39]: arr[range(3),range(3)]=None
In [40]: arr
Out[40]:
array([[None, 0, 0],
[0, None, 0],
[0, 0, None]], dtype=object)is None测试:
In [41]: arr is None
Out[41]: False==测试。
In [42]: arr == None
Out[42]:
array([[ True, False, False],
[False, True, False],
[False, False, True]])
In [43]: np.where(arr == None)
Out[43]: (array([0, 1, 2]), array([0, 1, 2]))比较测试在对象数组中的传播一直在进行一些更改。来自最近的一个release_notes:https://docs.scipy.org/doc/numpy-1.15.1/release.html#comparison-ufuncs-accept-dtype-object-overriding-the-default-bool
列表上的类似操作
In [44]: alist = [0,None,0]
In [45]: alist is None
Out[45]: False
In [46]: [i is None for i in alist]
Out[46]: [False, True, False]
In [48]: alist.index(None)
Out[48]: 1发布于 2018-11-16 20:26:57
由于某些原因,
np.where(col_entries is None)不返回属于None的元素的索引。
is操作符检查两个操作数是否指向同一个对象。因此,在这里它检查col_entries (矩阵)是否是None,因此它不执行“广播”来检查矩阵中的某些元素是否引用None。
在Python中,可以重载某些操作符,如<=、==等。Numpy利用它来实现特定的运算符,例如可以编写some_matrix == 0来生成布尔矩阵。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))https://stackoverflow.com/questions/53344789
复制相似问题