按照 Python 中的標準強制轉換規則確定常見型別


要按照標準強制轉換規則確定常見型別,請在 Python NumPy 中使用numpy.find_common_type()方法。第一個引數是表示陣列的 dtypes 或可轉換物件 dtypes 的列表。第二個引數是表示標量的 dtypes 或可轉換物件 dtypes 的列表。

find_common_type()方法返回通用資料型別,忽略scalar_types而使用array_types中的最大值,除非scalar_types的最大值的型別不同(dtype.kind)。如果不理解型別,則返回None。

步驟

首先,匯入必要的庫 −

import numpy as np

在 NumPy 中使用 find_common_type()方法。按照標準強制轉換規則確定常見型別 −

print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([], [np.int64, np.float32, complex]))
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([np.float32], [complex]))
print("Result...",np.find_common_type([np.float64], [complex]))
print("Result...",np.find_common_type(['f4', 'i4'], ['c8']))
print("Result...",np.find_common_type([np.int64], [complex]))
print("Result...",np.find_common_type([np.int64], [np.float64]))

示例

import numpy as np

# To determine common type following standard coercion rules, use the numpy.find_common_type() method in Python numpy
# The 1st argument is a list of dtypes or dtype convertible objects representing arrays.
# The 2nd argument is A list of dtypes or dtype convertible objects representing scalars.

print("Using the find_common_type() method in Numpy\n")

# Determine common type following standard coercion rules
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([], [np.int64, np.float32, complex]))
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([np.float32], [complex]))
print("Result...",np.find_common_type([np.float64], [complex]))
print("Result...",np.find_common_type(['f4', 'i4'], ['c8']))
print("Result...",np.find_common_type([np.int64], [complex]))
print("Result...",np.find_common_type([np.int64], [np.float64]))

輸出

Using the find_common_type() method in Numpy

Result... float32
Result... complex128
Result... float32
Result... complex128
Result... complex128
Result... complex128
Result... complex128
Result... float64

更新於: 24-2-2022

151 次瀏覽

助力您的職業生涯

完成課程認證

開始
廣告
© . All rights reserved.