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

ทำให้ทัพเพิลของลิสต์แบน (Flatten Tuple of List to Tuple) ใน Python


เมื่อต้องการทำให้ทัพเพิลที่มีโครงสร้างซ้อนซับซ้อนแบนเป็นทัพเพิลเดียวที่มีทัพเพิลย่อยเฉพาะระดับเดียว สามารถใช้ฟังก์ชันแบบเรียกซ้ำ

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

def flatten_tuple(t):
    if isinstance(t, tuple) and len(t) == 2 and not isinstance(t[0], tuple):
        return (t,)
    result = []
    for sub in t:
        result.extend(flatten_tuple(sub))
    return tuple(result)

my_tuple = ((35, 46), ((67, 70), (8, 11), (10, 111)), ((21, 12), (3, 4)))
print("The tuple is:")
print(my_tuple)
print("The flattened tuple is:")
print(flatten_tuple(my_tuple))

ผลลัพธ์

The tuple is: ((35, 46), ((67, 70), (8, 11), (10, 111)), ((21, 12), (3, 4)))
The flattened tuple is: ((35, 46), (67, 70), (8, 11), (10, 111), (21, 12), (3, 4))

คำอธิบาย

  • ฟังก์ชัน flatten_tuple ตรวจสอบว่าเป็นทัพเพิลคู่ที่ไม่ซ้อน (base case)

  • ถ้าเป็น base case คืนค่าเป็นทัพเพิลที่ห่อไว้: (t,)

  • ถ้าไม่ใช่ ให้วนลูปผ่านองค์ประกอบ เรียกซ้ำ และรวมผลลัพธ์ด้วย extend

  • คืนค่าเป็นทัพเพิลแบนแล้ว