python 生成器

python 生成器一共两种创建方法:

1,(x for x in range(5))

2,yield

生成器:(generator object)

创建生成器两种方式:
1,(x*2  for x in range(10))
2, def  f():
      yield 2
      print ("ok")
    f()           只会打印出2  >>>>>yield看成return!!!

生成器的方法:
next (f())----------计算出一个值

注意: 生成器在创建的时候已经决定了能计算出值的个数,调用next的次数超过这个值就会报SopIteration的错误。
3,send()
f().send(None) #等价于 next(f())

例如:

# vim 3.py

def fib(max):
n,before,after = 0,0,1
while n < max:
yield before
before,after = after,before+after
n += 1

g = fib(8)
print (next(g))
print (next(g))
print (next(g))
print (next(g))
print (next(g))
print (next(g))
print (next(g))
print (next(g))

 

[root@localhost python]# python 3.py
0
1
1
2
3
5
8
13

 

# vim 4.py
def bar():
  print ("ok1")     #1

  count = yield 1
  print (count)

  yield 2


b = bar()
next(b)

ret = b.send("eeeeeeeeeeeeeeeee")
print (ret)

运行结果:

[root@localhost python]# python 4.py
ok1
eeeeeeeeeeeeeeeee
2
看现象。。。。。

 

posted @ 2018-02-04 12:42  lixinliang  阅读(150)  评论(0编辑  收藏  举报