生成器

#__author__:Administrator}
#data: 2017/11/28
#生成器两种创建方式
#方式一
# s = (x*2 for x in range(5))
# print(s)#<generator object <genexpr> at 0x000001F7534FB2B0>
# print(next(s))
# #等价于print(__next__())
# print(next(s))
# print(next(s))
# print(next(s))
# print(next(s))
# print(next(s))


##############################
#生成器就是一个可迭代对象Iterable
# s = (x*2 for x in range(5))
# for i in s:
# print(i)

#方式二
# def foo():
# print('a')
# yield 1
#
# print('b')
# yield 2

# print(foo)#<function foo at 0x000002779069DBF8>

# g =foo()#生成器对象
# # print(g)#<generator object foo at 0x0000028FD044B2B0>
# print(next(g))
# print(next(g))


# #什么是可迭代对象(对象拥有__iter__(方法的称为可迭代对象)
# l = [1,2,3]
# l.__iter__()
# l = (1,2,3)
# l.__iter__()
# l = {'name':'xuxu'}
# l.__iter__()
#
# for i in [1,2,3]:
# print(i)


# def fib(max):
# x,before,after = 0,0,1
# while x<max:
# print(after)
# before,after = after,before+after
# x = x+1
#
# fib(5)

#改变成生成器
# def fib(max):
# x,before,after = 0,0,1
# while x<max:
# yield after
# before,after = after,before+after
# x = x+1
#
# g = fib(5)
# print(g)
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))

#生成器方式三
# def foo():
# print('a')
# count = yield 1
# print(count)
#
#
# yield 2
#
# b = foo()
# s = b.send(None)#next(b),第一次send前如果没有next,你只能传一个sand(None),跟next一样,只是send能传值
# print(s)
# ret=b.send('eee')
# print(ret)

posted @ 2017-12-01 17:51  无敌帅帅头  阅读(90)  评论(0编辑  收藏  举报