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

    list1 = iter([11,22,33,44,55,66,77,88,99])
    print (list1.__next__())
    print (list1.__next__())
    结果:
    11
    22
    结论:迭代器,只能取next的值。

    应用:
    fp = open("ha.bak")
    for line in fp:
    print (line.strip(' '))
    fp.close()

    with open("ha.bak",'r') as fp:
    for line1 in fp:
    print (line1.strip())

    在for line in fp中也可以使用for line in fp.readlines()函数,但是这样读起来效率很低,for line in fp可以像迭代器一样,一条一条的读入到内存中,不需要一次性读入。


    生成器:
    def fab(max):
    n = 0
    a = 0
    b = 1
    while n < max:
    yield b
    #print (b)
    a, b = b, a + b
    n = n + 1

    f = fab(5)
    print (f.__next__())
    print (f.__next__())
    print (f.__next__())
    print (f.__next__())
    print (f.__next__())
    print (f.__next__())
    使用yield参数相当于返回这样一个值(b),但是这样的返回不是作为函数的结束而返回的,而是像中断一样,下次你再访问的时候,还是从刚才那个中断开始。 

      1
      1
      2
      3
      5
      Traceback (most recent call last):
      File "D:/Python/day3/Test.py", line 20, in <module>
      print (f.__next__())
      StopIteration

      查看另外一个例子“

    def withdraw(account):
    while account > 0:
    account -= 100
    yield 1
    print ("withdraw again")

    f = withdraw(500)
    print (f.__next__())
    print ("first next")
    print (f.__next__())
    print ("second next")
    print (f.__next__())
    print ("third next")
    print (f.__next__())
    print ("fourth next")
    print (f.__next__())
    print ("fifth next")

      1
      first next
      withdraw again
      1
      second next
      withdraw again
      1
      third next
      withdraw again
      1
      fourth next
      withdraw again
      1
      fifth next

      在这个例子中,每次取100最多只能有五次取钱的机会。在print (f.__next__())函数中间可以增加其他的程序代码,而当迭代器再次回来运行的时候,还是从刚才保存的状态   开始。这样一个生产迭代器的函数叫做生成器。

  • 相关阅读:
    ssh免密码登录
    nginx做负载均衡+keepalived(做主备)
    centos之Too many open files问题-修改linux最大文件句柄数
    redis-JedisPoolConfig配置
    Hadoop端口说明
    hadoop 2.5 安装部署
    Java集合框架 10 连问,你有被问过吗?
    Dubbo面试八连问,这些你都能答上来吗?
    面试官:关于Java性能优化,你有什么技巧
    Docker从入门到掉坑(三):容器太多,操作好麻烦
  • 原文地址:https://www.cnblogs.com/python-study/p/5460346.html
Copyright © 2011-2022 走看看