List1 = ITER ([11,22,33,44,55,66,77,88,99])
Print (list1.__next__ ())
Print (list1.__next__ ())
Results:
11
22
Conclusion: The iterator can only take the next value.
Application:
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 ())
The for line in FP can also be used for the fp.readlines () function, but it is very inefficient to read, and the for-line in FP can be read into memory like an iterator without a one-time read-in.
Generator:
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__ ())
using the yield parameter is equivalent to returning a value (b), but such a return is not returned as the end of the function, but rather as an interruption, the next time you visit, or from that interrupt just before.
1
1
2
3
5
Traceback (most recent):
File "d:/python/day3/test.py", line A, in <module>
Print (f.__next__ ())
Stopiteration
See another example "
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):
File "d:/python/day3/test.py", line +, in <module>
Print (f.__next__ ())
Stopiteration
In this example, a maximum of 100 can be taken at most five of the time to withdraw money. You can add other program code in the middle of the print (f.__next__ ()) function, and when the iterator comes back to run, it starts with the state you just saved. Such a function of producing iterators is called generators.
Python iterators and generators