在 Python 中返回标量数据类型的字符串表示法


要返回标量数据类型的字符串表示法,可用 Python Numpy 中的 sctype2char() 方法。第一个参数(标量数据类型时),返回相应的字符串字符。如果是一个对象,sctype2char 会尝试推断它的标量类型,然后返回相应的字符串字符。

步骤

首先,导入所需的库——

import numpy as np

一个标量类型的字符串表示法——

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

返回 int 数据类型的字符串表示法——

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

返回 float 数据类型的字符串表示法——

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

示例

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))

输出

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

更新于: 2022-02-25

259 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.