Python中的迭代器和生成器区别

迭代器

class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self
    def __next__(self):
        if self.a <= 10:
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

if __name__ == '__main__':
    while True:
        print(next(myiter))

 

生成器

 1 def fibonacci(n): # 生成器函数 - 斐波那契
 2     a, b, counter = 0, 1, 0
 3     while True:
 4         if (counter > n): 
 5             return
 6         yield a
 7         a, b = b, a + b
 8         counter += 1
 9 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
10 
11 if __name__ == '__main__':
12     while True:
13         try:
14             print (next(f), end=" ")
15         except StopIteration:
16             sys.exit()

 

原文来源:

https://www.runoob.com/python3/python3-iterator-generator.html

 

上一篇:Jmeter 向 MySQL 插入大量数据


下一篇:统计序列中元素出现的频度并获取topK