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