Skip to content

Latest commit

 

History

History
28 lines (21 loc) · 421 Bytes

File metadata and controls

28 lines (21 loc) · 421 Bytes

生成器

generator

列表生成器

f = (x ** 2 for x in range(1, 1000))
print(sys.getsizeof(f))  # 相比生成式生成器不占用存储数据的空间
print(f)
for val in f:
    print(val)

yield关键字

将一个普通函数改造成生成器函数

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
        yield a
 
for val in fib(20):
    print(val)