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

ตรวจสอบว่า typecode ตัวแรกอยู่ต่ำกว่าหรือเท่ากันในลำดับชั้นชนิดข้อมูลด้วย Python


ภาพรวม

ใช้ numpy.issubdtype() เพื่อตรวจสอบว่า typecode ตัวแรกเป็น subtype (อยู่ต่ำกว่าหรือเท่ากัน) ของ typecode ตัวที่สองในลำดับชั้นชนิดข้อมูล (type hierarchy) ของ NumPy หรือไม่ คืนค่า True หรือ False

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

1. นำเข้า NumPy

import numpy as np

2. ทดสอบ issubdtype() กรณีต่างๆ

print("Result...", np.issubdtype(np.float64, np.float32))
print("Result...", np.issubdtype(np.float64, np.floating))
print("Result...", np.issubdtype(np.float32, np.floating))
print("Result...", np.issubdtype('i4', np.signedinteger))
print("Result...", np.issubdtype('i8', np.signedinteger))
print("Result...", np.issubdtype(np.int32, np.integer))

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

import numpy as np
print("Using the issubdtype() method in Numpy\n")
print("Result...", np.issubdtype(np.float64, np.float32))
print("Result...", np.issubdtype(np.float64, np.floating))
print("Result...", np.issubdtype(np.float32, np.floating))
print("Result...", np.issubdtype('i4', np.signedinteger))
print("Result...", np.issubdtype('i8', np.signedinteger))
print("Result...", np.issubdtype(np.int32, np.integer))

ผลลัพธ์

Using the issubdtype() method in Numpy
Result... False
Result... True
Result... True
Result... True
Result... True
Result... True

คำอธิบาย:

  • float64 ไม่ใช่ subtype ของ float32 (False)
  • float64 และ float32 เป็น subtype ของ floating (True)
  • 'i4' (int32) และ 'i8' (int64) เป็น subtype ของ signedinteger (True)
  • int32 เป็น subtype ของ integer (True)