在 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 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告