ในบทความนี้ เราจะเรียนรู้เกี่ยวกับฟังก์ชัน Iterator 4 ตัวที่มีใน Python 3.x หรือเวอร์ชันก่อนหน้า ได้แก่ accumulate(), chain(), filterfalse(), dropwhile()
ตอนนี้มาดูแต่ละตัวละเอียด
เมธอด accumulate() และ chain()
เมธอด accumulate() รับสองอาร์กิวเมนต์ หนึ่งคือ iterable ที่ต้องการดำเนินการ อีกหนึ่งคือฟังก์ชัน/การดำเนินการที่จะทำ โดยค่าเริ่มต้น อาร์กิวเมนต์ที่สองจะทำการบวก
เมธอด chain() จะพิมพ์เป้าหมาย iterable ทั้งหมดหลังจากต่อ (concatenate) iterable ทั้งหมดเข้าด้วยกัน
ตัวอย่างด้านล่างอธิบายการนำไปใช้งาน
ตัวอย่าง
import itertools
import operator as op
# เริ่มต้นลิสต์ 1
li1 = ['t', 'u', 't', 'o', 'r']
# เริ่มต้นลิสต์ 2
li2 = [1, 1, 1, 1, 1]
# เริ่มต้นลิสต์ 3
li3 = ['i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']
# ใช้ accumulate() เมธอดบวก
print("The sum after each iteration is : ", end="")
print(list(itertools.accumulate(li1, op.add)))
# ใช้ accumulate() เมธอดคูณ
print("The product after each iteration is : ", end="")
print(list(itertools.accumulate(li2, op.mul)))
# ใช้ chain() เมธอด
print("All values in mentioned chain are : ", end="")
print(list(itertools.chain(li1, li3)))
ผลลัพธ์
The sum after each iteration is : ['t', 'tu', 'tut', 'tuto', 'tutor'] The product after each iteration is : [1, 1, 1, 1, 1] All values in mentioned chain are : ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']
เมธอด dropwhile() และ filterfalse()
เมธอด dropwhile() รับฟังก์ชันเพื่อตรวจสอบเงื่อนไขและ iterable อินพุตที่ต้องการดำเนินการ มันคืนค่าทั้งหมดของ iterable หลังจากที่เงื่อนไขกลายเป็นเท็จ
เมธอด filterfalse() รับฟังก์ชันเพื่อตรวจสอบเงื่อนไขและ iterable อินพุตที่ต้องการดำเนินการ มันคืนค่าเมื่อเงื่อนไขที่กำหนดกลายเป็นเท็จ
ตัวอย่าง
import itertools
# ลิสต์
l = ['t', 'u', 't', 'o', 'r']
# ใช้ dropwhile() เมธอด
print("The values after condition fails : ", end="")
print(list(itertools.dropwhile(lambda x: x != 'o', l)))
# ใช้ filterfalse() เมธอด
print("The values when condition fails : ", end="")
print(list(itertools.filterfalse(lambda x: x != 'o', l)))
ผลลัพธ์
The values after condition fails : ['o', 'r'] The values when condition fails : ['o']
สรุป
ในบทความนี้ เราได้เรียนรู้เกี่ยวกับประเภทต่างๆ ของฟังก์ชัน Iterator ที่มีใน Python 3.x หรือเวอร์ชันก่อนหน้า