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))