14、生成器

生成器和yield

如果函数体包含yield关键字,再调用函数,并不会执行函数代码,而是返回一个生成器对象

def my_range(start, stop, step=1):
    print('start...')
    while start < stop:
        yield start
        start += step
    print('end...')


g = my_range(1, 5)
print(g)    # <generator object my_range at 0x000002F9EC4794A0>

生成器内置有__iter__方法和__next__方法,所以生成器是一个迭代器
因此可以使用next来触发函数的执行

def my_range(start, stop, step=1):
    print('start...')
    while start < stop:
        yield start
        start += step
    print('end...')


g = my_range(1, 5)
print(g)    # <generator object my_range at 0x000002F9EC4794A0>
next(g)		# 函数执行到yield时,会停下来
next(g)
next(g)
next(g)
next(g)		# 函数结束,抛出异常

生成器执行next方法,相当于执行参数为None的send方法,send方法可以把yield替换成send的参数

def eater():
    print('Ready to eat')
    while True:
        food = yield
        print('get the food: %s, and start to eat' % food)


g = eater()
next(g)
g.send('包子')
# Ready to eat
# get the food: 包子, and start to eat

yield表达式可以用来传递多个值,使用 变量名 = yield 值的形式

def eater():
    print('Ready to eat')
    food_list = []
    while True:
        food = yield food_list
        food_list.append(food)
        print(food_list)


e = eater()
next(e)
e.send('包子')

三元表达式

相当于python中的?表达式
res = 条件成立时返回的值 if 条件 else 条件不成立时返回的值

列表生成式

用于快速生成列表,用法如下

[expression for item1 in iterable1 if condition1
for item2 in iterable2 if condition2
...
for itemN in iterableN if conditionN
]

#类似于
res=[]
for item1 in iterable1:
    if condition1:
        for item2 in iterable2:
            if condition2
                ...
                for itemN in iterableN:
                    if conditionN:
                        res.append(expression)
egg_list=['鸡蛋%s' %i for i in range(10)]
print(egg_list)
# ['鸡蛋0', '鸡蛋1', '鸡蛋2', '鸡蛋3', '鸡蛋4', '鸡蛋5', '鸡蛋6', '鸡蛋7', '鸡蛋8', '鸡蛋9']

生成器表达式

(expression for item in iterable if condition)
生成器表达式返回的是一个生成器对象

posted @ 2021-08-15 15:18  晴天々⊙雨天  阅读(35)  评论(0)    收藏  举报