Python iterators and generators

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.