python yield的使用

def simple():
    x = 0
    yield x
    yield x + 1
    yield x + 2


def simple2():
    x = 0
    yield x
    yield x + 1
    yield x + 2


test = simple()
test2 = simple2()

print(type(test))
# 查看函数返回的对象类型<class 'generator'>

# 两种方法实现遍历生成器元素
# 方法一:
for i in test:
    print(i)

# 方法二:
print(next(test2))
print(next(test2))
print(next(test2))

关键词yield行为类似return,都是向函数返回值,只是,他返回后并不清场,继续血战到底.直到没有可返回的数据,每一次调用既完成返回且保留调用位置信息,下次调用继续完成后续工作,每一次的节点在调用yield后结束,下次从yield后面的语句开始执行.

遍历生成器

def example():
    temp = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"]
    x = 0
    for x in range(12):
        yield temp[x]


print(type(example()))

说明:

1、内涵合法yield的函数 返回 generator(生成器)对象。

2、yield每次向建立的临时环境中加入元素。

def example():
    zodiac = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"]

    x = 0
    for x in range(12):
        print("begin------" + str(x))
        yield zodiac[x]
        print("end--------" + str(x))


temp = example()
next(temp)
next(temp)
next(temp)
next(temp)
next(temp)
next(temp)
next(temp)
next(temp)
next(temp)
next(temp)
next(temp)
next(temp)

每调用一次yield来返回数据后,便保留一个环境信息或调用地址,下次next时,从上一次暂停的返回地址继续生成新数据.这样保存的仅仅是运行期临时地址,不会占用大量内存,否则就需要静态建立大量内存的列表来实现.

def example():
    zodiac = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"]

    x = 0
    while True:
        if x > 11:
            x = 0
        print("begin------" + str(x))
        yield zodiac[x]
        x += 1
        print("end--------" + str(x))


temp = example()

print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))
print(next(temp))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

正月龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值