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

การคูณ Tuple แบบ Element-wise ใน Python

Tuple Multiplication (Element-wise) ใน Python

เมื่อต้องการคูณ Tuple สองตัวแบบ Element-wise (คูณค่าที่ Index ตรงกัน) สามารถใช้ zip() และ Generator Expression ได้

zip() และ Generator

  • zip(): รวม Iterables หลายตัวเป็น Iterator ของ Tuple
  • Generator: สร้าง Iterator แบบ Lazy Evaluation ประหยัดหน่วยความจำ

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

my_tuple_1 = (23, 45, 12, 56, 78)
my_tuple_2 = (89, 41, 76, 0, 11)

print("The first tuple is : ")
print(my_tuple_1)
print("The second tuple is : ")
print(my_tuple_2)

# zip รวมคู่คู่ แล้วคูณกัน
my_result = tuple(elem_1 * elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))

print("The multiplied tuple is : ")
print(my_result)

ผลลัพธ์

The first tuple is : (23, 45, 12, 56, 78)
The second tuple is : (89, 41, 76, 0, 11)
The multiplied tuple is : (2047, 1845, 912, 0, 858)

คำอธิบาย

  • กำหนด Tuple 2 ตัว ความยาวเท่ากัน และแสดงผล
  • ใช้ zip() จับคู่ Element ที่ Index ตรงกัน
  • Generator Expression คูณค่าคู่กัน (elem_1 * elem_2)
  • แปลงเป็น Tuple ด้วย tuple()
  • เก็บผลลัพธ์และแสดง

การคำนวณแบบละเอียด

IndexTuple 1Tuple 2ผลคูณ
023892047
145411845
21276912
35600
47811858

กรณี Tuple ความยาวไม่เท่ากัน

t1 = (1, 2, 3, 4)
t2 = (10, 20)
result = tuple(a * b for a, b in zip(t1, t2))
print(result)  # (10, 40) - zip หยุดที่ Tuple สั้นกว่า

ใช้ NumPy สำหรับข้อมูลขนาดใหญ่

import numpy as np
t1 = (23, 45, 12, 56, 78)
t2 = (89, 41, 76, 0, 11)
result = tuple(np.array(t1) * np.array(t2))
print(result)  # (2047, 1845, 912, 0, 858) - เร็วกว่าสำหรับข้อมูลมาก