生成器

#生成器一共两种创建方式
# 1.(x*2 for x in range(5))
# 2.yield

s = (x*2 for x in range(2))
print(s)

print(next(s)) #等价于print(s.__next__()) in py2: s.next()
print(next(s))
print(next(s))
print(next(s))
print(next(s))
print(next(s))
#for i in range(100):
# print(next(s))

s = (x*2 for x in range(100000000000))
print(s)

#print(next(s)) #等价于print(s.__next__()) in py2: s.next()

for i in s: #生成器就是一个可迭代对象(Iterable)
print(i)




2.
def foo():
print("ok")
yield 'tt'
print('ok2')
yield 2

g=foo()
# print(g)

for i in foo():
print(i)
posted @ 2019-07-08 19:59  python小白丶  阅读(128)  评论(0编辑  收藏  举报