python中的迭代器和生成器

2022-03-24  本文已影响0人  韩其凯

迭代器

ls = [1,2,3,4,5,6,7]
ls_ = iter(ls)
next(ls_)  # 1
next(ls_)  # 2
next(ls_)  # 3
······
class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self
 
  def __next__(self):
    x = self.a
    self.a += 1
    return x
 
myclass = MyNumbers()
myiter = iter(myclass)
 
print(next(myiter))  # 1
print(next(myiter))  # 2
print(next(myiter))  # 3
print(next(myiter))  # 4
print(next(myiter))  # 5

生成器

import sys
 
def fibonacci(n): # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): 
            return
        yield a
        a, b = b, a + b
        counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
    try:
        print (next(f), end=" ")
    except StopIteration:
        sys.exit()
# 0 1 1 2 3 5 8 13 21 34 55
上一篇 下一篇

猜你喜欢

热点阅读