Numpy算术

Numpy arithmetic

我有以下代码:

import numpy as np
x=np.array([[3, 5, 1]])
print(x.shape) #get (1,3)
np.multiply(x.shape, 8) #get [ 8, 24]

print(*x.shape) # get 1 3
np.array((np.multiply(*x.shape), 8)) #get [3, 8]

请解释 why/how np.multiply(*x.shape, 8) 得到 [3, 8] ?

发生的事情是通过做

np.multiply(*x.shape)

您正在使用 * 运算符解包元组 (1,3),并将每个元素作为参数传递给 np.multiply。所以结果是 1*3 也就是 3。

然后,您只是将其结果包装到 8 的数组中,所以您最终得到的数组是 [3, 8]

* 解压可迭代对象。所以如果 x.shape(1,3) 并且你调用 np.multiply(*x.shape) 你实际上会调用 np.multiply(1,3) 得到 38 只是硬编码,所以没什么特别的。

另外,因为你写了它:8 不是 这里 np.multiply 的参数。