Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

คืนค่าตัวแทน string ของ scalar dtype ใน Python


ภาพรวม

ใช้ numpy.sctype2char() คืนค่าตัวอักษร (character) ที่แทน scalar dtype ถ้าเป็น scalar dtype จะคืน character ตรงกัน ถ้าเป็น object จะพยายาม infer scalar type แล้วคืน character

ขั้นตอนการทำงาน

1. นำเข้า NumPy

import numpy as np

2. แสดง string representation ของ scalar types ต่างๆ

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

3. String representation ของ int types

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

4. String representation ของ float types

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

ตัวอย่างโค้ดเต็ม

import numpy as np
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))
print("\nThe string representation of int types...")
for j in [np.int16, np.int32, np.int64]:
    print(np.sctype2char(j))
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

ตารางสรุป:

TypeChar
int16h
int32i
int64l
float16e
float32f
float64d
complex64F
complex128D
string_S
ndarrayO