在 Python 中返回相同種類但精度最高的標量型別


若要返回相同型別的最高精度標量型別,在 Python Numpy 中使用 maximum_sctype() 方法。引數是輸入資料型別。它可以是 dtype 物件或可轉換為 dtype 的物件。

步驟

首先,匯入所需的庫 −

import numpy as np

使用 Numpy 中的 maximum_sctype() 方法。獲取最高精度的標量型別 −

print("Result...",np.maximum_sctype(int))
print("Result...",np.maximum_sctype(np.uint8))
print("Result...",np.maximum_sctype(complex))
print("Result...",np.maximum_sctype(str))
print("Result...",np.maximum_sctype('f4'))
print("Result...",np.maximum_sctype('i2'))
print("Result...",np.maximum_sctype('i4'))
print("Result...",np.maximum_sctype('i8'))

範例

import numpy as np

# To return the scalar type of highest precision of the same kind as the input, use the maximum_sctype() method in Python Numpy
# The parameter is the input data type. This can be a dtype object or an object that is convertible to a dtype.
print("Using the maximum_sctype() method in Numpy\n")

# Get the scalar type of highest precision
print("Result...",np.maximum_sctype(int))
print("Result...",np.maximum_sctype(np.uint8))
print("Result...",np.maximum_sctype(complex))
print("Result...",np.maximum_sctype(str))
print("Result...",np.maximum_sctype('f4'))
print("Result...",np.maximum_sctype('i2'))
print("Result...",np.maximum_sctype('i4'))
print("Result...",np.maximum_sctype('i8'))

輸出

Using the maximum_sctype() method in Numpy

Result... <class 'numpy.int64'>
Result... <class 'numpy.uint64'>
Result... <class 'numpy.complex256'>
Result... <class 'numpy.str_'>
Result... <class 'numpy.float128'>
Result... <class 'numpy.int64'>
Result... <class 'numpy.int64'>
Result... <class 'numpy.int64'>

更新日期: 2022-02-25

108 瀏覽次數

開啟您的事業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.