• 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__())函数中间可以增加其他的程序代码,而当迭代器再次回来运行的时候,还是从刚才保存的状态   开始。这样一个生产迭代器的函数叫做生成器。

  • 相关阅读:
    【原创】解决向工程中添加Megacore 文件在文件列表中没有出现目标文件的问题
    (笔记)找工作,该怎么进补
    (原创)结构体位域操作
    (原创)TCP/IP学习笔记之IP(网际协议)
    (原创)确认大端模式或小端模式(最直接有效的方法)
    (原创)HDL中的unsigned与signed
    (原创)TCP/IP学习笔记之概述
    (笔记)往一个指定的地址读写一个值
    (笔记)我的EDN博客被评为专家博客啦
    (原创)同步复位与异步复位
  • 原文地址:https://www.cnblogs.com/python-study/p/5460346.html
Copyright © 2020-2023  润新知