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

คืนค่าชนิดสเกลาร์ร่วมของอาร์เรย์อินพุตใน Python

ในการคืนค่าชนิดสเกลาร์ที่ร่วมกันของอาร์เรย์อินพุต ใช้เมธอด numpy.common_type() ใน NumPy พารามิเตอร์แรกคืออาร์เรย์อินพุต ชนิดคืนค่าจะเป็น inexact (จุดลอยตัว) เสมอ แม้อาร์เรย์ทั้งหมดจะเป็นจำนวนเต็ม หากอินพุตหนึ่งเป็นอาร์เรย์จำนวนเต็ม ชนิดความแม่นยำขั้นต่ำที่คืนคือ 64-bit floating point dtype

อาร์เรย์อินพุตทั้งหมดยกเว้น int64 และ uint64 สามารถแปลงเป็น dtype ที่คืนค่าได้อย่างปลอดภัยโดยไม่สูญเสียข้อมูล

ขั้นตอน

ขั้นแรก ให้นำเข้าไลบรารี:

import numpy as np

ใช้ numpy.common_type() เพื่อหาชนิดสเกลาร์ร่วม:

print("Using the common_type() method in Numpy\n")
print("Result...", np.common_type(np.arange(3, dtype=np.float32)))
print("Result...", np.common_type(np.arange(3, dtype=np.float32), np.arange(2)))
print("Result...", np.common_type(np.arange(3), np.array([22, 2.j]), np.array([32.9])))
print("Result...", np.common_type(np.arange(3), np.array([22, 39]), np.array([32.9])))
print("Result...", np.common_type(np.arange(3, dtype=np.int32), np.arange(2)))

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

import numpy as np
# คืนค่าชนิดสเกลาร์ร่วมของอาร์เรย์อินพุต
# ใช้ numpy.common_type() ใน Python NumPy
# พารามิเตอร์แรกคืออาร์เรย์อินพุต
print("Using the common_type() method in Numpy\n")
print("Result...", np.common_type(np.arange(3, dtype=np.float32)))
print("Result...", np.common_type(np.arange(3, dtype=np.float32), np.arange(2)))
print("Result...", np.common_type(np.arange(3), np.array([22, 2.j]), np.array([32.9])))
print("Result...", np.common_type(np.arange(3), np.array([22, 39]), np.array([32.9])))
print("Result...", np.common_type(np.arange(3, dtype=np.int32), np.arange(2)))

ผลลัพธ์

Using the common_type() method in Numpy
Result... <class 'numpy.float32'>
Result... <class 'numpy.float64'>
Result... <class 'numpy.complex128'>
Result... <class 'numpy.float64'>
Result... <class 'numpy.float64'>