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

Python – รวมสมาชิกตัวสุดท้ายของ Tuple ในลิสต์

เมื่อต้องการรวม (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() รวมสตริงทั้งหมดด้วยช่องว่างเป็นตัวคั่น

  • แสดงผลลัพธ์ที่ได้