生成器

xiaoxiao2021-02-28  21

# 1. 列表生成式修改为生成器 li = [i for i in range(100) if i%2==0] # 生成器 g = (i for i in range(100) if i%2==0) # # # # 2. 查看生成器内容的两种方式 # # ## 2-1.python3中 g.__next__方法(), python2.x中g.next(); # python2.x, python3.x, next(g) print(g.__next__()) ##运行一次输出一次 print(g.__next__()) print(g.__next__()) print(next(g)) # ## 2-2. for循环 from collections import Iterable print(isinstance(g, Iterable)) # # for i in g: # print(i) while True: try: print(g.__next__()) except StopIteration: # print('end') break def gen(): while True: try: yield 'a' except TypeError: print('type error') # throw方法:给生成器发送一个异常(错误); 但是不影响g.__next__()的执行; # close(): 关闭生成器, 再次执行g.__next__()报错; g = gen() print(g.__next__()) g.throw(TypeError) print(g.__next__()) 1 a type error a # 当在函数中看到yield关键字, 那么这个函数调用的返回值是一个生成器; def fib(num): ## a, b, count = 0, 1, 1 # 0, 1 while count <= num: yield b a, b = b, a + b #a=2, b=3 count += 1 g = fib(10) for i in g: print(i)

1 1 2 3 5 8 13 21 34 55

yield关键字

# 1. 当在函数中看到yield关键字, 那么这个函数调用的返回值是一个生成器; # 2. 当要执行函数fun时, 必须调用g.__next__(); # 3. 函数执行时, 直到遇到yield停止; # 4. 想要继续执行, 调用g.__next__();从上一次停止的地方继续执行; def fun(): a = "world" print("hello") print(1) yield 2 print(3) yield 4 g = fun() print(g) for i in g: # g.__next__() print(i) <generator object fun at 0x7fb57e85ceb8> ##generator hello 1 2 3 4
转载请注明原文地址: https://www.6miu.com/read-2603278.html

最新回复(0)