码迷,mamicode.com
首页 > 编程语言 > 详细

Python 迭代器和生成器

时间:2016-05-05 01:57:30      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

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(‘\n‘))
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 100
print ("withdraw again")

f = withdraw(500)
print (f.__next__())
print (f.__next__())
print (f.__next__())
print (f.__next__())
print (f.__next__())
print (f.__next__())

  100
  withdraw again
  100
  withdraw again
  100
  withdraw again
  100
  withdraw again
  100
  withdraw again
  Traceback (most recent call last):
  File "D:/Python/day3/Test.py", line 16, in <module>
  print (f.__next__())
  StopIteration

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

Python 迭代器和生成器

标签:

原文地址:http://www.cnblogs.com/python-study/p/5460346.html

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