返回應用 NumPy 型別提升規則到 Python 引數後得到的結果型別


NumPy 的 `numpy.result_type()` 方法返回應用 NumPy 型別提升規則到引數後得到的結果型別。第一個引數是某些操作的運算元,需要知道其結果型別。NumPy 中的型別提升與 C++ 等語言中的規則類似,但也有一些細微的差別。當同時使用標量和陣列時,陣列的型別優先,並且會考慮標量的實際值。

步驟

首先,匯入所需的庫:

import numpy as np

NumPy 的 `numpy.result_type()` 方法返回應用 NumPy 型別提升規則到引數後得到的結果型別:

print("Using the result_type() method in Numpy\n")
print("Result...",np.result_type(2, np.arange(4,dtype='i1')))
print("Result...",np.result_type(5, 8))
print("Result...",np.result_type('i4', 'c8'))
print("Result...",np.result_type(3.8, 8))
print("Result...",np.result_type(5, 20.7))
print("Result...",np.result_type(-8, 20.7))
print("Result...",np.result_type(10.0, -4))

示例

import numpy as np
# The numpy.result_type() method returns the type that results from applying the NumPy type promotion rules to the arguments.
# The 1st parameter is the operands of some operation whose result type is needed.
print("Using the result_type() method in Numpy\n")

print("Result...",np.result_type(2, np.arange(4,dtype='i1')))
print("Result...",np.result_type(5, 8))
print("Result...",np.result_type('i4', 'c8'))
print("Result...",np.result_type(3.8, 8))
print("Result...",np.result_type(5, 20.7))
print("Result...",np.result_type(-8, 20.7))
print("Result...",np.result_type(10.0, -4))

輸出

Using the result_type() method in Numpy

Result... int8
Result... int64
Result... complex128
Result... float64
Result... float64
Result... float64
Result... float64

更新於: 2022年2月24日

114 次檢視

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告