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

กำหนดชนิดข้อมูลร่วมตามกฎการบังคับมาตรฐานใน Python

ในการกำหนดชนิดข้อมูลร่วมตามกฎการบังคับมาตรฐาน (standard coercion rules) ใช้เมธอด numpy.find_common_type() ใน NumPy อาร์กิวเมนต์แรกคือรายการ dtypes หรือออบเจ็กต์ที่แปลงเป็น dtype ได้ แทนอาร์เรย์ อาร์กิวเมนต์ที่สองคือรายการ dtypes หรือออบเจ็กต์ที่แปลงเป็น dtype ได้ แทนสเกลาร์

เมธอด find_common_type() ส่งคืนชนิดข้อมูลร่วม ซึ่งเป็นค่าสูงสุดของ array_types โดยไม่สนใจ scalar_types เว้นแต่ค่าสูงสุดของ scalar_types จะเป็น kind ต่างกัน (dtype.kind) หาก kind ไม่เข้าใจ จะส่งคืน None

ขั้นตอน

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

import numpy as np

ใช้ find_common_type() กำหนดชนิดร่วม:

print("Result...", np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...", np.find_common_type([], [np.int64, np.float32, complex]))
print("Result...", np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...", np.find_common_type([np.float32], [complex]))
print("Result...", np.find_common_type([np.float64], [complex]))
print("Result...", np.find_common_type(['f4', 'i4'], ['c8']))
print("Result...", np.find_common_type([np.int64], [complex]))
print("Result...", np.find_common_type([np.int64], [np.float64]))

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

import numpy as np
# กำหนดชนิดร่วมตามกฎการบังคับมาตรฐาน
# ใช้ numpy.find_common_type() ใน Python numpy
# อาร์กิวเมนต์แรก: รายการ dtypes แทนอาร์เรย์
# อาร์กิวเมนต์ที่สอง: รายการ dtypes แทนสเกลาร์
print("Using the find_common_type() method in Numpy\n")
# กำหนดชนิดร่วมตามกฎการบังคับมาตรฐาน
print("Result...", np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...", np.find_common_type([], [np.int64, np.float32, complex]))
print("Result...", np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...", np.find_common_type([np.float32], [complex]))
print("Result...", np.find_common_type([np.float64], [complex]))
print("Result...", np.find_common_type(['f4', 'i4'], ['c8']))
print("Result...", np.find_common_type([np.int64], [complex]))
print("Result...", np.find_common_type([np.int64], [np.float64]))

ผลลัพธ์

Using the find_common_type() method in Numpy
Result... float32
Result... complex128
Result... float32
Result... complex128
Result... complex128
Result... complex128
Result... complex128
Result... float64