从中减去选择a
,找到结果最小值的索引,代入。
a = np.array([[0, 0, 0], [4, 4, 4], [9, 9, 9]])
choices = np.array([1, 5, 10])
b = a[:,:,None] - choices
np.absolute(b,b)
i = np.argmin(b, axis = -1)
a = choices[i]
print a
>>>
[[ 1 1 1]
[ 5 5 5]
[10 10 10]]
a = np.array([[0, 3, 0], [4, 8, 4], [9, 1, 9]])
choices = np.array([1, 5, 10])
b = a[:,:,None] - choices
np.absolute(b,b)
i = np.argmin(b, axis = -1)
a = choices[i]
print a
>>>
[[ 1 1 1]
[ 5 10 5]
[10 1 10]]
>>>
额外的维度被添加到a
使得每个元素choices
将从每个元素中减去a
. choices
was 播送 https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html反对a
在三维空间中,这个链接有一个不错的图形 http://www.scipy-lectures.org/intro/numpy/operations.html#broadcasting. b.shape
是 (3,3,3)。Erics广播文档 https://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc是一个很好的解释,最后有一个图形 3D 示例。
对于第二个例子:
>>> print b
[[[ 1 5 10]
[ 2 2 7]
[ 1 5 10]]
[[ 3 1 6]
[ 7 3 2]
[ 3 1 6]]
[[ 8 4 1]
[ 0 4 9]
[ 8 4 1]]]
>>> print i
[[0 0 0]
[1 2 1]
[2 0 2]]
>>>
最终作业使用索引数组 https://docs.scipy.org/doc/numpy/user/basics.indexing.html#index-arrays or 整数数组索引 https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html.
在第二个示例中,请注意有一个tie对于元素a[0,1]
,可以替换一个或五个。