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

Trả về True nếu ép kiểu giữa kiểu vô hướng và 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ề True nếu vô hướng và kiểu dữ liệu có thể xảy ra theo quá trình ép kiểu. Tham số đầu tiên là kiểu vô hướng hoặc 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

Kiểm tra xem vô hướng và kiểu dữ liệu có thể xảy ra theo quy tắc truyền hay không. -

print("Checking with can_cast() method in Numpy\n")
print("Result...",np.can_cast(20, 'i1'))
print("Result...",np.can_cast(280, 'i1'))
print("Result...",np.can_cast(80, 'u1'))
print("Result...",np.can_cast(300.7, np.float32))
print("Result...",np.can_cast(120.6, np.float64))
print("Result...",np.can_cast(7.2e100, np.float32))
print("Result...",np.can_cast(6.5e100, np.float64))

Ví dụ

import numpy as np

# The numpy.can_cast() method returns True if scalar and data type can occur according to the casting rule.
# The 1st parameter is the scalar or 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(20, 'i1'))
print("Result...",np.can_cast(280, 'i1'))
print("Result...",np.can_cast(80, 'u1'))
print("Result...",np.can_cast(300.7, np.float32))
print("Result...",np.can_cast(120.6, np.float64))
print("Result...",np.can_cast(7.2e100, np.float32))
print("Result...",np.can_cast(6.5e100, np.float64))

Đầu ra

Checking with can_cast() method in Numpy

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