Computer >> Máy Tính >  >> Lập trình >> Python

Trả về True nếu ép kiểu giữa các kiểu dữ liệu có thể xảy ra theo quy tắc ép kiểu trong Python

Phương thức numpy.can_cast () trả về giá trị True nếu việc ép kiểu giữa các kiểu dữ liệu có thể xảy ra theo quy tắc dự báo. Tham số đầu tiên là kiểu dữ liệu hoặc mảng để truyền từ đó. Tham số thứ 2 là kiểu dữ liệu để truyền tới.

Các bước

Đầu tiên, hãy nhập thư viện được yêu cầu -

import numpy as np

Sử dụng can_cast () để kiểm tra xem có thể truyền giữa các kiểu dữ liệu theo quy tắc truyền hay không -

print("Checking with can_cast() method in Numpy\n")
print("Result...",np.can_cast(np.int32, np.int64))
print("Result...",np.can_cast(np.float64, complex))
print("Result...",np.can_cast(complex, float))
print("Result...",np.can_cast('i8', 'f8'))
print("Result...",np.can_cast('i8', 'f4'))
print("Result...",np.can_cast('i4', 'S4'))

Ví dụ

import numpy as np

# The numpy.can_cast() method returns True if cast between data types can occur according to the casting rule.
# The 1st parameter is the data type or array to cast from.
# The 2nd parameter is the data type to cast to.

print("Checking with can_cast() method in Numpy\n")
print("Result...",np.can_cast(np.int32, np.int64))
print("Result...",np.can_cast(np.float64, complex))
print("Result...",np.can_cast(complex, float))
print("Result...",np.can_cast('i8', 'f8'))
print("Result...",np.can_cast('i8', 'f4'))
print("Result...",np.can_cast('i4', 'S4'))

Đầu ra

Checking with can_cast() method in Numpy

Result... True
Result... True
Result... False
Result... True
Result... False
Result... False