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

ตัวอย่างการใช้ Lambda และ Filter ใน Python

ในบทช่วยสอนนี้ เราจะดูตัวอย่างการใช้ lambda expression และฟังก์ชัน filter() ใน Python

Lambda Expression

ใช้เขียนฟังก์ชันเล็กๆ แบบ anonymous (ไม่มีชื่อ) แบบ one-liner

filter(function, iterable)

กรองสมาชิกใน iterable คืนค่า filter object (แปลงเป็น list ได้) เฉพาะสมาชิกที่ function คืนค่า True

ตัวอย่าง: กรองเลขคู่จาก List

Input: nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output: [2, 4, 6, 8, 10]

อัลกอริทึม

1. กำหนด list ตัวเลข
2. ใช้ filter() ร่วมกับ lambda x: x % 2 == 0
3. แปลง filter object เป็น list
4. พิมพ์ผลลัพธ์

โค้ด

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

result = filter(lambda x: x % 2 == 0, nums)
print(list(result))

ผลลัพธ์

[2, 4, 6, 8, 10]

ตัวอย่างเพิ่มเติม: กรองสตริงที่ขึ้นต้นด้วย 'a'

words = ['apple', 'banana', 'avocado', 'cherry', 'apricot']
result = filter(lambda w: w.startswith('a'), words)
print(list(result))

ผลลัพธ์

['apple', 'avocado', 'apricot']

สรุป

filter() ร่วมกับ lambda ทำให้กรองข้อมูลได้สั้นและอ่านง่าย (Pythonic) เหมาะสำหรับ functional programming style หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น