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

กำหนดว่า object ที่ให้มาประกอบ scalar data-type หรือไม่ใน Python


ภาพรวม

ใช้ numpy.issctype() ตรวจสอบว่า object ที่ให้มาประกอบ scalar data-type หรือไม่ คืนค่า Boolean

  • True: ถ้า rep เป็น instance ของ scalar dtype
  • False: ถ้าไม่ใช่ (รวมถึง scalar values เช่น int, float ตรงๆ)

พารามิเตอร์

  • rep: object ที่ต้องการตรวจสอบ

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

1. นำเข้า NumPy

import numpy as np

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

print("Result...", np.issctype(np.int32))
print("Result...", np.issctype(np.int64))
print("Result...", np.issctype(np.dtype('str')))
print("Result...", np.issctype(100))
print("Result...", np.issctype(25.9))
print("Result...", np.issctype(np.float32(22.3)))

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

import numpy as np
print("Using the issctype() method in Numpy\n")
print("Result...", np.issctype(np.int32))
print("Result...", np.issctype(np.int64))
print("Result...", np.issctype(np.dtype('str')))
print("Result...", np.issctype(100))
print("Result...", np.issctype(25.9))
print("Result...", np.issctype(np.float32(22.3)))

ผลลัพธ์

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

คำอธิบาย:

  • np.int32, np.int64, np.dtype('str') เป็น scalar dtype classes → True
  • 100 (Python int), 25.9 (Python float), np.float32(22.3) (scalar instance) → False เพราะไม่ใช่ dtype class

ประโยชน์: ใช้ตรวจสอบว่า object เป็น dtype class ก่อนนำไปใช้ใน type-related operations