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

สามารถใช้ Generator สร้าง Iterator ใน Python ได้หรือไม่?

ใช่ เราสามารถสร้าง Generator โดยใช้ Iterator ใน Python การสร้าง Iterator นั้นง่ายดาย เราสามารถสร้าง Generator โดยใช้คำสำคัญ yield

Generator ใน Python เป็นวิธีที่ง่ายและเรียบง่ายในการสร้าง Iterator และใช้หลักเพื่อประกาศฟังก์ชันที่ทำงานเหมือน Iterator

Generator คือฟังก์ชันที่เราสามารถวนลูปเพื่อรับค่าทีละค่า ในชีวิตประจำวันของโปรแกรมเมอร์ จะใช้วัตถุที่วนซ้ำได้ (iterable) เช่น list, string, dict เป็นต้น

Iterator คือวัตถุที่สามารถวนซ้ำผ่านลูปได้

ตัวอย่างต่อไปนี้แสดงว่า Generator นำคำสั่ง yield มาใช้ใน Python ซึ่งทำงานคล้ายกับการคืนค่า

ตัวอย่าง

def generator():
    print("program working sucessfully")
    yield 'x'
    yield 'y'
    yield 'z'

generator()

ผลลัพธ์

<generator object generator at 0x000000CF81D07390>

เราสามารถใช้ for loop เพื่อสร้าง Generator ได้เช่นกัน

ตัวอย่าง

for i in generator():
    print(i)

ผลลัพธ์

program working sucessfully
x
y
z

วัตถุ Iterator รองรับสองเมธอดคือ 1. __iter__ และ 2. __next__

  • เมธอด __iter__ คืนค่าวัตถุ Iterator เอง ใช้หลักกับ for loop และคำสั่ง in
  • เมธอด __next__ คืนค่าถัดไปจาก Iterator หากไม่มีรายการเหลือแล้ว จะระบุข้อยกเว้น StopIteration

ตัวอย่าง

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

c = Counter(3, 20)
for i in c:
    print(i, end=' ')

ผลลัพธ์

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20