ในบทความนี้ เราจะเรียนรู้เกี่ยวกับฟังก์ชันตัววนซ้ำสี่ฟังก์ชันที่มีอยู่ใน Python 3.x หรือก่อนหน้านั้น สะสม() , chain(), กรอง false() , วิธีการ dropwhile()
ทีนี้มาดูรายละเอียดแต่ละอันกัน –
วิธีสะสม () &chain()
วิธีสะสม () รับสองอาร์กิวเมนต์ หนึ่งสามารถทำซ้ำเพื่อดำเนินการและอีกฟังก์ชัน / การดำเนินการที่จะดำเนินการ โดยค่าเริ่มต้น อาร์กิวเมนต์ที่สองจะดำเนินการเพิ่ม
เมธอด Chain() พิมพ์เป้าหมายที่ทำซ้ำได้ทั้งหมดหลังจากเชื่อมต่อ iterables ทั้งหมดแล้ว
ตัวอย่างด้านล่างอธิบายการใช้งาน −
ตัวอย่าง
import itertools
import operator as op
# initializing list 1
li1 = ['t','u','t','o','r']
# initializing list 2
li2 = [1,1,1,1,1]
# initializing list 3
li3 = ['i','a','l','s','p','o','i','n','t']
# using accumulate() add method
print ("The sum after each iteration is : ",end="")
print (list(itertools.accumulate(li1,op.add)))
# using accumulate() multiply method
print ("The product after each iteration is : ",end="")
print (list(itertools.accumulate(li2,op.mul)))
# using chain() method
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()
Drop while() method ยอมรับฟังก์ชันเพื่อตรวจสอบเงื่อนไขและอินพุตที่ iterable เพื่อดำเนินการ ส่งกลับค่าทั้งหมดของ iterable หลังจากที่เงื่อนไขกลายเป็นเท็จ
วิธีการ Filterfalse() ยอมรับฟังก์ชันเพื่อตรวจสอบเงื่อนไขและอินพุตที่ทำซ้ำได้ ส่งคืนค่าเมื่อเงื่อนไขที่กำหนดกลายเป็นเท็จ
ตัวอย่าง
import itertools
# list
l = ['t','u','t','o','r']
# using dropwhile() method
print ("The values after condition fails : ",end="")
print (list(itertools.dropwhile(lambda x : x!='o',l)))
# using filterfalse() method
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']
บทสรุป
ในบทความนี้ เราได้เรียนรู้เกี่ยวกับฟังก์ชันตัววนซ้ำประเภทต่างๆ ที่มีอยู่ใน Python 3.x หรือก่อนหน้านั้น