1. The iterator saves memory
Iterators allow read-only data and do not allow readback of data
The iterator cannot skip reading the file because he is 1.1 points to load the contents of the file into memory, read it can be destroyed or discarded
2. Generate an Iterator
A = ITER (["FD", "SS", "DD", "FF"])
3. Iterator Method:
python3.0 above: __next__ (); Python2.7:next ()
A.__next__ () is reading the FD
A.__NEXT__ () Read the SS
A.__NEXT__ () is read by DD
A.__NEXT__ () Read the FF
A.__NEXT__ () will prompt for an error, stop the iteration
4, the cat, more, less and other methods in Linux are similar to the iterator effect
5, the use of iterators:
f = Open (* * * *)
For line in F://Similar to 2.7 inside Xreadlines ()
Print (line)
This kind of reading is the iterative way of reading, so read faster.
Much higher efficiency than f.read () and F.readlines ()
6. Generator Generator
When a function call returns an iterator, the function is called the generator, and if the function contains the yield syntax, the function becomes the generator
6.1
def cash (amount):
While amount > 0:
Amount-= 100
Yield 100//This keyword has done a return operation here at this time
Print ("I am a generator")
ATM = Cash (500)
Print (atm.__next__ ())
Print (atm.__next__ ())
Print ("Jump out of functions and loops at any time")//is equivalent to an asynchronous operation
Print (atm.__next__ ())
Print (atm.__next__ ())
Print (atm.__next__ ())
6.2
Import time
DEF consumer (name):
Print ("%s ready to eat Buns"% name)
While True:
Baozi = yield//This time yield as a container for receiving values
Print ("Bun [%s] came, was [%s] ate")
def producer (name):
C1 = Consumer (' A ')
C2 = consumer (' B ')
C1.__NEXT__ ()//in order to print the first sentence "ready to eat steamed buns!"
C2.__NEXT__ ()//in order to print the first sentence "ready to eat steamed buns!"
Print ("Lao Zi started making buns")
For I in range (10):
Time.sleep (1)
Print ("Made of 2 buns")
C1.send (i)
C2.send (i)
Producer ("hehe")
Python Learning iterator and generator