💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、豆包、星火、月之暗面及文生图、文生视频 广告
`generator` 定义 ---- 定义:可以理解为一种数据类型,存储算法而非实际数据。边循环边计算。 特点:边循环边计算,不生成完整的list,节省大量空间 创建生成器 ------------ 1.生成器表达式 ~~~ g = (x for x in range(9)) # <generator object <genexpr> at 0x0000000001E299E8> next(g) # 0 next(g) # 1 ~~~ 2.生成器函数(使用`yield`关键字) python解释器会将带有`yield`关键字的函数视为生成器,函数返回一个iterable对象。 函数执行到`yield`处,将值添加到iterable对象,然后从`yield`位置处继续执行。 ~~~ # 自然数生成器: def natural(): num = 0 while True: num += 1 yield num natural # <function natural at 0x00000000031A1D90> n = natural() # <generator object natural at 0x00000000031FE360> print(next(n)) # 1 print(next(n)) # 2 ~~~ 检测 ----- `functools.Generator` ~~~ from collections import Generator g = (x for x in []) isinstance(g, Generator) # True ~~~ 生成器是迭代器 ---------------- 生成器是迭代器,故: 1. **惰性**:只能遍历一次 2. 会产生StopIteration错误 - next()到头,没有更多元素时,下次next()会返回StopIteration错误 - 无法直接取得生成器函数返回值,返回值包含在StopIteration错误中,可以捕获错误取得返回值 ~~~ # generator只能遍历一次 g = (x*x for x in range(2)) for x in g: print(x) # 0 1 for x in g: print(x) # 无输出 ~~~ ~~~ # 获取生成器函数返回值 def gene(): n = 0 while True: n += 1 if n < 3: yield n else: return 'hello' n = gene() try: next(n) next(n) next(n) next(n) except StopIteration as e: print(e) # hello ~~~ 练习 ----- 创建自然数的平方的数列 ~~~ def nsquare(): n = 1 while True: yield n*n n = n + 1 ~~~ 创建斐波那契数列 ~~~ def fib(): a, b = 0, 1 while True: yield b a, b = b, a + b ~~~ 创建杨辉三角 ~~~ def yhtriangle(n): l, index = [1], 0 while index < n: yield l l = [1]+[ l[x]+l[x+1] for x in range(len(l)-1) ]+[1] index += 1 ~~~