zoukankan      html  css  js  c++  java
  • Python迭代器和生成器

    '''list = [1,2,3,4]
    it = iter(list)
    print(next(it))
    print(next(it))
    
    #for x in it:
     #   print(x,end=' ')
    
    import sys
    while True:
        try:
            print(next(it))
        except StopIteration:
            sys.exit()
    '''
    
    # 迭代器,实现__iter__,__next__
    class MyNumber:
        def __iter__(self):
            self.a = 1
            return self
        def __next__(self):
            x = self.a
            self.a +=1
            return x
    
    myclass = MyNumber()
    for i in myclass:
        print(i)
        if i > 20:
            break
    
    # 生成器,使用 yield 的函数,有yield函数即为生成器
    # 每次遇到yield时,函数暂停保存信息
    
    import sys
    
    def fibonacci(n):
        a = 0
        b = 1
        cnt = 0
    
        while True:
            if(cnt > n):
                return
            yield a
            a , b = b, a + b
            cnt+=1
    
    f = fibonacci(10)
    
    while True:
        try:
            print(next(f), end=" ")
        except StopIteration:
            sys.exit()

    还有反向迭代器__reversed__,生成器表达式,等等。

  • 相关阅读:
    Celery
    windows笔记目录
    Linux笔记目录
    python笔记目录
    rsa
    c#目录
    webpack3.x配置
    RabbitMQ服务安装(Linux)
    JavaScript验证用户输入
    IP地址检测工具
  • 原文地址:https://www.cnblogs.com/TreeDream/p/10031093.html
Copyright © 2011-2022 走看看