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

แปลง Tuple เป็น Matrix ขนาด N×N ใน Python

บทนำ

การแปลง tuple ของ tuples (ขนาดไม่เท่ากัน) ให้กลายเป็น matrix ขนาด N×N โดยเติมค่า (เช่น 0) ให้แต่ละแถวยาวเท่ากับ N สามารถทำได้ด้วยลูปและออปเปอเรเตอร์ *

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

tuple_of_tuples = ((11, 14), (0, 78), (33, 11), (10, 78))
N = 4
print("Tuple เดิม:", tuple_of_tuples)
print("N =", N)

result = []
for tup in tuple_of_tuples:
    # คำนวณจำนวนศูนย์ที่ต้องเติม: N - ความยาวปัจจุบัน
    padding = (0,) * (N - len(tup))
    # ต่อ tuple เดิมกับ padding
    new_row = tup + padding
    result.append(new_row)

print("Matrix N×N:", result)

ผลลัพธ์

Tuple เดิม: ((11, 14), (0, 78), (33, 11), (10, 78))
N = 4
Matrix N×N: [(11, 14, 0, 0), (0, 78, 0, 0), (33, 11, 0, 0), (10, 78, 0, 0)]

คำอธิบาย

  • วนลูปแต่ละ inner tuple
  • (0,) * (N - len(tup)) สร้าง tuple ของศูนย์จำนวนที่ต้องเติม
  • tup + padding ต่อ tuple เดิมกับ padding
  • เก็บในลิสต์ผลลัพธ์ (หรือแปลงเป็น tuple ของ tuples)

รูปแบบ List Comprehension

result = [tup + (0,) * (N - len(tup)) for tup in tuple_of_tuples]
# หรือเป็น tuple of tuples:
result = tuple(tup + (0,) * (N - len(tup)) for tup in tuple_of_tuples)