สร้าง N-Element Incremental Tuples
เมื่อต้องการสร้าง Tuple ที่แต่ละ Element เป็น Tuple ย่อยที่มีค่าเพิ่มขึ้นทีละ N สามารถใช้ Generator Expression และ tuple() ได้
ตัวอย่างโค้ด
N = 3
print("The value of 'N' has been initialized")
print("The number of times it has to be repeated is : ")
print(N)
# สร้าง Tuple ของ Tuple: (1,1,1), (2,2,2), ...
my_result = tuple((elem,) * N for elem in range(1, 6))
print("The tuple sequence is : ")
print(my_result)
ผลลัพธ์
The value of 'N' has been initialized The number of times it has to be repeated is : 3 The tuple sequence is : ((1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5))
คำอธิบาย
- กำหนด N = 3 (จำนวนครั้งที่ซ้ำ)
- ใช้
range(1, 6)สร้างเลข 1-5 (elem,) * Nสร้าง Tuple ที่มี elem ซ้ำ N ครั้ง (คอมม่าสำคัญสำหรับ Tuple 1 Element)- Generator Expression สร้าง Sequence ของ Tuple เหล่านี้
- แปลงเป็น Tuple นอกสุดด้วย
tuple() - แสดงผล
การทำงานของ (elem,) * N
elem = 3
N = 3
print((elem,) * N) # (3, 3, 3)
# (elem,) คือ Tuple หนึ่ง Element
# * N ทำซ้ำ Tuple N ครั้ง
รูปแบบอื่นๆ
# เริ่มจาก 0
tuple((elem,) * N for elem in range(5))
# ((0,0,0), (1,1,1), (2,2,2), (3,3,3), (4,4,4))
# Step อื่น
tuple((elem,) * N for elem in range(1, 10, 2))
# ((1,1,1), (3,3,3), (5,5,5), (7,7,7), (9,9,9))
# ใช้ List Comprehension แล้วแปลง
tuple([(elem,) * N for elem in range(1, 6)])
การประยุกต์: สร้าง Matrix แบบ Diagonal
N = 3
# สร้าง Identity Matrix pattern
matrix = tuple((1 if i == j else 0 for j in range(N)) for i in range(N))
print(matrix)
# ((1, 0, 0), (0, 1, 0), (0, 0, 1))