out 引數

numpy dot 函式有一個可選引數 out = None。此引數允許你指定要將結果寫入的陣列。此陣列的形狀和型別必須與返回的陣列完全相同,否則將引發異常。

>>> I = np.eye(2)
>>> I
array([[ 1.,  0.],
       [ 0.,  1.]])
>>> result = np.zeros((2,2))
>>> result
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> np.dot(I, I, out=result)
array([[ 1.,  0.],
       [ 0.,  1.]])
>>> result
array([[ 1.,  0.],
       [ 0.,  1.]])

讓我們嘗試將結果的 dtype 更改為 int。

>>> np.dot(I, I, out=result)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: output array is not acceptable (must have the right type, nr dimensions, and be a C-Array)

如果我們嘗試使用不同的底層記憶體順序,比如 Fortran 風格(因此列是連續的而不是行),也會產生錯誤。

>>> result = np.zeros((2,2), order='F')
>>> np.dot(I, I, out=result)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: output array is not acceptable (must have the right type, nr dimensions, and be a C-Array)