zoukankan      html  css  js  c++  java
  • 2019-02-02 Python学习——生成器杨辉三角,迭代器与可迭代对象的区别

    练习

    杨辉三角定义如下:

         	  1
       		 / 
     	    1   1
      	   /  / 
     	  1   2   1
    	 /  /  / 
    	1   3   3   1
       /  /  /  / 
      1   4   6   4   1
     /  /  /  /  / 
    1   5   10  10  5   1
    

    把每一行看做一个list,试写一个generator,不断输出下一行的list:

    def triangles():
        list = [1]
        while list:
            yield list
            newlist = list.copy()#进行一次深复制
            for i in range(len(list)+1):
                if(i==0):
                    pass
                elif(i==len(list)):
                    newlist.append(1)
                elif(i!=0 and i!=len(list)):
                    newlist[i] = list[i] + list[i-1]
            list = newlist.copy()
    
    

    廖雪峰网站上的题目,贴一下自己的

    网上更简单的

    def triangles():
        list = [1]
        while True:
            yield list
            list = [list[i]+list[i+1] for i in range(len(list)-1)]
            list.insert(0,1)
            list.append(1)
            
    

    insert没有想到哎

    迭代器和可迭代对象

    from collections import Iterable
    from collections import Iterator
    isinstance( , Iterable) #用于判断是否为可迭代对象
    isinstance( , Iterator) #用于判断是否为迭代器
    

    总结

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

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

    集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
    (来自廖雪峰官网)


    就酱

  • 相关阅读:
    Android Camera 使用小结
    Android 调用堆栈跟踪
    读取文件
    Android USB大容量存储时SD卡状态监听(转)
    Setting up PhoneGap on Ubuntu for Android app development
    python单元测试
    python数据库备份
    python多线程多进程
    python面向对象编程和类
    python异常处理及Url编码
  • 原文地址:https://www.cnblogs.com/roccoshi/p/13027104.html
Copyright © 2011-2022 走看看