列表生成器
# 列表生成式 lst = [] for i in range(10): lst.append(i * 2) print(lst) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # 相当于: lst = [i * 2 for i in range(10)] print(lst) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # 列表生成器:循环迭代,推断下一元素 lst = (i * 2 for i in range(10)) print(lst) # <generator object <genexpr> at 0x0000000004200CF0> """生成器: 只用调用是才会生成相应的数据 只记录当前位置 只有一个__next__() """
yield生成器
# 菲波那切数列Fibonacci def fib(max): # 此时不能叫函数,应该叫生成器 n = 0 a, b = 0, 1 while n < max: yield b # 返回当前值,并保存当前状态 a, b = b, a+b # 同时赋值 n = n+ 1 return "异常消息" # 输出异常信息 f = fib(10) print("===") print(f.__next__()) # 下一个值 print("===") print(f.__next__()) print("==start loop==") # for i in f: # print(i) while True: try: g = next(f) print(g) except StopIteration as e: print("value of e :", e.value) break """OUT: === 1 === 1 ==start loop== 2 3 5 8 13 21 34 55 value of e : 异常消息 """