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

บวก Tuples แบบ Element-wise ใน Python

บทนำ

การบวก tuple ทีละ element (element-wise addition) เช่น (1,2) + (3,4) = (4,6) สามารถทำได้ด้วย map() ร่วมกับ lambda หรือใช้ zip() ร่วมกับ list comprehension

ตัวอย่างโค้ด (map + lambda)

tuple1 = (11, 14, 54, 56, 87)
tuple2 = (98, 0, 10, 13, 76)

print("Tuple 1:", tuple1)
print("Tuple 2:", tuple2)

# ใช้ map และ lambda บวกทีละคู่
result = tuple(map(lambda x, y: x + y, tuple1, tuple2))

print("ผลบวก:", result)

ผลลัพธ์

Tuple 1: (11, 14, 54, 56, 87)
Tuple 2: (98, 0, 10, 13, 76)
ผลบวก: (109, 14, 64, 69, 163)

คำอธิบาย

  • map(lambda x, y: x + y, tuple1, tuple2) ใช้ lambda บวกคู่ละคู่
  • tuple(...) แปลง map object กลับเป็น tuple
  • หากความยาวต่างกัน จะหยุดที่สั้นกว่า (เหมือน zip)

วิธีอื่น: zip + List Comprehension (แนะนำ)

result = tuple(x + y for x, y in zip(tuple1, tuple2))
print(result)  # (109, 14, 64, 69, 163)

วิธีนี้อ่านง่ายกว่า และเป็น Pythonic มากกว่า

ใช้ NumPy (สำหรับข้อมูลมาก/คำนวณหนัก)

import numpy as np
result = tuple(np.array(tuple1) + np.array(tuple2))
print(result)