Rear Element Extraction from List of Tuples
เมื่อต้องการดึงเอลีเมนต์ตัวสุดท้าย (Rear/Last Element) จากทุก Tuple ใน List of Tuples สามารถใช้ List Comprehension และ Negative Indexing ได้
ตัวอย่างโค้ด
my_list = [('Will', 67, 45), ('Jam', 34, 56), ('Pow', 99, 123), ('Nyk', 0, 56)]
print("The list of tuples is : ")
print(my_list)
# List Comprehension: ดึง Index -1 (ตัวสุดท้าย) ของแต่ละ Tuple
my_result = [lis[-1] for lis in my_list]
print("The list of tuples with only rear tuple element is : ")
print(my_result)
ผลลัพธ์
The list of tuples is : [('Will', 67, 45), ('Jam', 34, 56), ('Pow', 99, 123), ('Nyk', 0, 56)]
The list of tuples with only rear tuple element is : [45, 56, 123, 56]
คำอธิบาย
- สร้าง List of Tuples (แต่ละ Tuple มี 3 Elements: Name, Num1, Num2) และแสดงผล
- List Comprehension:
[lis[-1] for lis in my_list] lis[-1]เข้าถึง Element ตัวสุดท้ายของแต่ละ Tuple (Negative Index)- รวมผลลัพธ์เป็น List ใหม่
- แสดงผล
การทำงานแบบละเอียด
| Tuple | Index 0 | Index 1 | Index 2 (-1) | Extracted |
|---|---|---|---|---|
| ('Will', 67, 45) | Will | 67 | 45 | 45 |
| ('Jam', 34, 56) | Jam | 34 | 56 | 56 |
| ('Pow', 99, 123) | Pow | 99 | 123 | 123 |
| ('Nyk', 0, 56) | Nyk | 0 | 56 | 56 |
ดึง Element ตำแหน่งอื่นๆ
my_list = [('Will', 67, 45), ('Jam', 34, 56), ('Pow', 99, 123), ('Nyk', 0, 56)]
# Front element (Index 0)
front = [t[0] for t in my_list]
print(front) # ['Will', 'Jam', 'Pow', 'Nyk']
# Middle element (Index 1)
middle = [t[1] for t in my_list]
print(middle) # [67, 34, 99, 0]
# ทุก Element (Flatten)
all_elements = [elem for t in my_list for elem in t]
print(all_elements) # ['Will', 67, 45, 'Jam', 34, 56, 'Pow', 99, 123, 'Nyk', 0, 56]
# ดึงหลาย Index พร้อมกัน
selected = [(t[0], t[-1]) for t in my_list]
print(selected) # [('Will', 45), ('Jam', 56), ('Pow', 123), ('Nyk', 56)]
ใช้ zip(*list) - Unzip (Transpose)
# Unzip: แยก Columns
names, nums1, nums2 = zip(*my_list)
print(names) # ('Will', 'Jam', 'Pow', 'Nyk')
print(nums1) # (67, 34, 99, 0)
print(nums2) # (45, 56, 123, 56) ← Rear Elements
# แปลงเป็น List
print(list(nums2)) # [45, 56, 123, 56]
กรณี Tuple ความยาวไม่เท่ากัน
my_list = [(1, 2), (3, 4, 5), (6,)]
# ใช้ try/except หรือเช็คความยาว
rear = [t[-1] for t in my_list if t] # ข้าม Tuple ว่าง
print(rear) # [2, 5, 6]