为什么[]和[[]]在numpy操作中有所不同

时间:2018-04-26 13:44:57

标签: python numpy

为什么我会得到以下

的不同答案
l = np.array([1,-2.6])
s = np.array([[1,-2.6]])
l = np.dot(l.T,l)
s = np.dot(s.T,s)
print l,s

输出

7.76 [[ 1.   -2.6 ]
 [-2.6   6.76]]

同样在以下情况

s = np.array([[ 1.,  -2.6],
 [-1.,   0.4],
 [-1.,  -0.6],
 [ 0.,   2.4],
 [ 1.,   0.4]]
)

打印元素会在没有[[]]

的情况下显示结果
print s[0,:]
[1.  -2.6]

1 个答案:

答案 0 :(得分:1)

看看这些物体的形状

l = np.array([1,-2.6])

>>> l.shape
(2, 1)
>>> l.T.shape
(1, 2)

#  (1,2)-dim matrix * (2,1)-dim matrix = (1,1)-dim matrix
>>> np.dot(l.T, l)
7.76

s = np.array([[1,-2.6]])
>>> s.shape
(1, 2)
>>> s.T.shape
(2, 1)

# (2,1)-dim matrix * (1,2)-dim matrix = (2,2)-dim matrix
>>> np.dot(s.T,s)
[[ 1.   -2.6 ]
 [-2.6   6.76]]