numpy.divmod#

numpy.divmod(x1, x2, [out1, out2, ]/, [out=(None, None), ]*, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature]) = <ufunc 'divmod'>#

同時回傳逐元素的商和餘數。

np.divmod(x, y) 等同於 (x // y, x % y),但速度更快,因為它避免了多餘的工作。它用於在 NumPy 陣列上實作 Python 內建函數 divmod

參數:
x1array_like

被除數陣列。

x2array_like

除數陣列。如果 x1.shape != x2.shape,它們必須可廣播到一個共同的形狀(這將成為輸出的形狀)。

outndarray、None 或 ndarray 和 None 的元組,選用

結果儲存的位置。如果提供,則必須具有輸入廣播到的形狀。如果未提供或為 None,則會回傳新分配的陣列。元組(僅可能作為關鍵字引數)的長度必須等於輸出數量。

wherearray_like,選用

此條件會廣播到輸入上。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他位置,out 陣列將保留其原始值。請注意,如果透過預設 out=None 建立未初始化的 out 陣列,則其中條件為 False 的位置將保持未初始化。

**kwargs

對於其他僅限關鍵字的引數,請參閱 ufunc 文件

回傳值:
out1ndarray

來自 floor division 的逐元素商。如果 x1x2 都是純量,則這是一個純量。

out2ndarray

來自 floor division 的逐元素餘數。如果 x1x2 都是純量,則這是一個純量。

參見

floor_divide

等同於 Python 的 // 運算子。

remainder

等同於 Python 的 % 運算子。

modf

對於正數 x,等同於 divmod(x, 1),但回傳值已切換。

範例

>>> import numpy as np
>>> np.divmod(np.arange(5), 3)
(array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))

divmod 函數可以用作 ndarray 上 np.divmod 的簡寫。

>>> x = np.arange(5)
>>> divmod(x, 3)
(array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))