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

ตรวจสอบว่า cast ระหว่างชนิดข้อมูลได้หรือไม่ โดยควบคุมกฎการ cast ใน Python


ภาพรวม

numpy.can_cast() คืน True ถ้า cast ระหว่างชนิดข้อมูลได้ตามกฎ casting rule ที่ระบุ

พารามิเตอร์

  • from_: dtype หรืออาร์เรย์ต้นทาง
  • to: dtype ปลายทาง
  • casting: กฎการ cast ('no', 'equiv', 'safe', 'same_kind', 'unsafe')

กฎการ Cast

  • 'no': ห้าม cast เลย
  • 'equiv': เปลี่ยน byte-order เท่านั้น
  • 'safe': cast ที่รักษาค่าได้ (ไม่สูญเสียข้อมูล)
  • 'same_kind': safe cast หรือ cast ใน kind เดียวกัน (เช่น float64→float32)
  • 'unsafe': cast ได้ทุกอย่าง

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

1. นำเข้า NumPy

import numpy as np

2. ทดสอบ can_cast() ด้วยกฎต่างๆ

print("Checking with can_cast() method in Numpy\n")
# 'no'
print("Result...", np.can_cast('i8', 'i8', 'no'))
print("Result...", np.can_cast('i8', 'no'))
# 'equiv'
print("Result...", np.can_cast('i8', 'equiv'))
print("Result...", np.can_cast('i8', 'equiv'))
# 'safe'
print("Result...", np.can_cast('i4', 'i8', 'safe'))
print("Result...", np.can_cast('i8', 'i4', 'safe'))
# 'same_kind'
print("Result...", np.can_cast('i8', 'i4', 'same_kind'))
print("Result...", np.can_cast('i8', 'i4', 'same_kind'))

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

import numpy as np
print("Checking with can_cast() method in Numpy\n")
print("Result...", np.can_cast('i8', 'i8', 'no'))
print("Result...", np.can_cast('i8', 'no'))
print("Result...", np.can_cast('i8', 'equiv'))
print("Result...", np.can_cast('i8', 'equiv'))
print("Result...", np.can_cast('i4', 'i8', 'safe'))
print("Result...", np.can_cast('i8', 'i4', 'safe'))
print("Result...", np.can_cast('i8', 'i4', 'same_kind'))
print("Result...", np.can_cast('i8', 'i4', 'same_kind'))

ผลลัพธ์

Checking with can_cast() method in Numpy
Result... True
Result... False
Result... True
Result... False
Result... True
Result... False
Result... True
Result... True

คำอธิบาย:

  • 'no': เหมือนกันทุกอย่าง (byte-order รวม) → True, byte-order ต่างกัน → False
  • 'equiv': byte-order ต่างกันได้ → True, ขนาดต่างกัน → False
  • 'safe': int32→int64 ปลอดภัย (True), int64→int32 ไม่ปลอดภัย (False)
  • 'same_kind': int64→int32 same kind (signed int) → True