码迷,mamicode.com
首页 > 其他好文 > 详细

生成器与迭代器

时间:2018-09-17 19:52:57      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:generator   获得   div   tuple   可迭代对象   列表   序列   tuples   alt   

迭代器:具有一个next()函数

凡是可作用于for循环的对象都是Iterable类型;

凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;

集合数据类型如listdictstr等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。

 

a = [1,2,3,4,,5]
for x in a:
 print x

 

生成器:也是一个可迭代对象

yield每次产生一个值(使用yield),函数就会被冻结,即函数停在那点等待被重新唤醒

def fib2(num):
    a,b,c = 0,0,1
    while a < num:
       #print c
        yield c #含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator
        b,c = c, b+c 
        a=a+1

 迭代器实现杨辉三角

预期效果:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]

def triangles():
    n = [1]
    while True:
        yield n  #生成器函数的标志
        n = [x+y for x,y in zip([0] + n,n+[0])]#生成一个列表,内包含[1],[1,1]....等
        
n = 0
for t in triangles():#迭代输出
    print(t)
    n = n + 1
    if n == 10:
        break
zip([iterable, ...])
zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压)。
技术分享图片

 

 

生成器与迭代器

标签:generator   获得   div   tuple   可迭代对象   列表   序列   tuples   alt   

原文地址:https://www.cnblogs.com/Just-for-myself/p/9663478.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!