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

การกรอง Tuple ด้วย K-th Element จาก List ใน Python

Filter Tuples by K-th Element from List

เมื่อต้องการกรอง Tuple จาก List of Tuples โดยใช้ K-th Element ตรวจสอบกับ List อีก List หนึ่ง สามารถใช้ List Comprehension และ Operator in ได้

คำอธิบาย

  • List of Tuple = List ที่แต่ละ Element เป็น Tuple
  • Operator in ตรวจสอบว่าค่าอยู่ใน Iterable หรือไม่
  • List Comprehension เขียน Loop แบบสั้น

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

my_list = [(1, 21), (25, 'abc', 'mnq'), (89, 45.65)]
print("The check list has been initialized")

check_list = [1, 25, 10, 21]
print("The list is :")
print(my_list)

k = 1
print("The 'k' value has been initialized to 1")

# กรอง Tuple ที่ Element Index k อยู่ใน check_list
my_result = [elem for elem in my_list if elem[k] in check_list]

print("The filtered tuples are : ")
print(my_result)

ผลลัพธ์

The check list has been initialized
The list is : [(1, 21), (25, 'abc', 'mnq'), (89, 45.65)]
The 'k' value has been initialized to 1
The filtered tuples are : [(1, 21)]

คำอธิบาย

  • กำหนด List of Tuples (ความยาว Tuple ไม่เท่ากันได้)
  • กำหนด Check List สำหรับตรวจสอบ
  • กำหนด K = 1 (ตรวจสอบ Element Index 1 คือตัวที่ 2)
  • List Comprehension: [elem for elem in my_list if elem[k] in check_list]
  • Tuple (1, 21): elem[1] = 21 อยู่ใน check_list ✓
  • Tuple (25, 'abc', 'mnq'): elem[1] = 'abc' ไม่อยู่ใน check_list ✗
  • Tuple (89, 45.65): elem[1] = 45.65 ไม่อยู่ใน check_list ✗
  • แสดงผล Tuple ที่ผ่านเงื่อนไข

กรณี K Index เกินความยาว Tuple

# จะเกิด IndexError ถ้า Tuple สั้นกว่า k+1
# ควรเพิ่มเงื่อนไขเช็คความยาว
my_result = [elem for elem in my_list if len(elem) > k and elem[k] in check_list]

กรองหลาย Column

# กรอง Tuple ที่ Index 0 อยู่ใน list1 และ Index 1 อยู่ใน list2
list1 = [1, 25]
list2 = [21, 'abc']
result = [t for t in my_list if len(t) > 1 and t[0] in list1 and t[1] in list2]
print(result)  # [(1, 21), (25, 'abc', 'mnq')]