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

หาชนิดข้อมูลที่มีขนาดเล็กที่สุดและ scalar kind เหมือนกันที่ cast ได้ปลอดภัยใน Python


ภาพรวม

numpy.promote_types() คืนค่าชนิดข้อมูล (dtype) ที่มีขนาดเล็กที่สุดและ scalar kind เล็กที่สุด ที่ type1 และ type2 สามารถ cast ได้อย่างปลอดภัย ผลลัพธ์อยู่ใน native byte order เสมอ

พารามิเตอร์

  • type1: ชนิดข้อมูลแรก
  • type2: ชนิดข้อมูลที่สอง

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

1. นำเข้า NumPy

import numpy as np

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

print("Result...", np.promote_types('f4', 'f8'))
print("Result...", np.promote_types('i8', 'f4'))
print("Result...", np.promote_types('>i8', '

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

import numpy as np
print("Checking with promote_types() method in Numpy\n")
print("Result...", np.promote_types('f4', 'f8'))
print("Result...", np.promote_types('i8', 'f4'))
print("Result...", np.promote_types('>i8', '

ผลลัพธ์

Checking with promote_types() method in Numpy
Result... float64
Result... float64
Result... complex128
Result... |S11
Result... int64
Result... complex128
Result... complex128

คำอธิบาย:

  • f4 (float32) + f8 (float64) → float64
  • i8 (int64) + f4 (float32) → float64
  • >i8 (big-endian int64) + (little-endian complex64) → complex128
  • i4 (int32) + S8 (string 8 bytes) → |S11 (string 11 bytes)
  • int32 + int64 → int64
  • float64 + complex → complex128
  • complex + float → complex128