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

Trả về biểu diễn chuỗi của một kiểu vô hướng trong Python

Để trả về biểu diễn chuỗi của một kiểu vô hướng, hãy sử dụng phương thức sctype2char () trong PythonNumpy. Đối số thứ nhất, nếu là kiểu vô hướng, thì ký tự chuỗi tương ứng sẽ được trả về. Nếu anobject, sctype2char cố gắng suy ra kiểu vô hướng của nó và sau đó trả về ký tự chuỗi tương ứng.

Các bước

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

import numpy as np

Biểu diễn chuỗi của kiểu vô hướng -

for i in [np.int32, np.double, np.complex_, np.string_, np.ndarray]:
   print(np.sctype2char(i))

Trả về biểu diễn chuỗi của các kiểu int -

print("\nThe string representation of int types...")
for j in [np.int16, np.int32,np.int64]:
   print(np.sctype2char(j))

Trả về biểu diễn chuỗi của các kiểu float -

print("\nThe string representation of float types...")
for j in [np.float16, np.float32,np.float64]:
   print(np.sctype2char(j))

Ví dụ

import numpy as np

# To return the string representation of a scalar dtype, use the sctype2char() method in Python Numpy
# The 1st argument, if a scalar dtype, the corresponding string character is returned.
# If an object, sctype2char tries to infer its scalar type and then return the corresponding string character.
print("The string representation of a scalar type...")
for i in [np.int32, np.double, np.complex_, np.string_, np.ndarray]:
   print(np.sctype2char(i))

# Return the string representation of int types
print("\nThe string representation of int types...")
for j in [np.int16, np.int32,np.int64]:
   print(np.sctype2char(j))

# Return the string representation of float types
print("\nThe string representation of float types...")
for j in [np.float16, np.float32,np.float64]:
   print(np.sctype2char(j))

Đầu ra

The string representation of a scalar type...
i
d
D
S
O

The string representation of int types...
h
i
l

The string representation of float types...
e
f
d