เมื่อต้องการรวม (concatenate) สมาชิกตัวสุดท้ายของทุก tuple ในลิสต์ สามารถใช้ list comprehension และเมธอด join() ได้
ตัวอย่าง
my_tuple = [(13, 42, "Will"), (48, "is a"), ("good boy",)]
print("The tuple is : ")
print(my_tuple)
my_result = " ".join([sub[-1] for sub in my_tuple])
print("The result is : ")
print(my_result)
ผลลัพธ์
The list is : [(13, 42, 'Will'), (48, 'is a'), ('good boy',)]
The concatenated list is : Will is a good boy
คำอธิบาย
กำหนดลิสต์ของ tuple ที่มีสมาชิกตัวสุดท้ายเป็นสตริง และแสดงผล
ใช้ list comprehension ดึงสมาชิกตัวสุดท้าย (
sub[-1]) ของแต่ละ tupleใช้
join()รวมสตริงทั้งหมดด้วยช่องว่างเป็นตัวคั่นแสดงผลลัพธ์ที่ได้