13 iterators and generators
I. iterators
1. Use the Dir function to see all the definitions in the class
2.__iter__ The iterator used to get the current object
3.__next__ Gets an element that iterates over an object
s= "I love hot pot"
Ret=dir (s) # See all the methods defined in the string s
print (ret)
it=s.__iter__ () # iterator used to get the current object
print (it.__next__ ()) # Gets the elements of an iterator object first
print (it.__next__ ())
print (it.__next__ ())
print (it.__next__ ())
print (it.__next__ ()) # after the last element. Continue __next__ will error stop iteration
def func (): # iterate through an iterative object element at a time
lst = []
for I in range (0, 10000):
Lst.append ("Costume" +str (i))
return LST
Print (func ())
def func ():
For i in range (0,10000):
yield "Costume" +str (i)
Gen=func ()
for I in Range (0,65): # Batches take elements on demand
ret=gen.__next__ ()
print (ret)
two. Generator
1. What is a generator? The builder is essentially an iterator.
2. There are three types in Python to get the generator:
(1) through the generator function
def func ():
Print ((111))
yield "222"
Gen=func () # If there is yield in the function, this function is the generator function
ret=gen.__next__ () # generator is essentially an iterator that can be executed directly __next__ ()
print (ret)
(2) The difference between yield and return.
#there is yield in the program, the function is the generator function, the access generator function, the function does not execute, returns a generator.
# The generator executes __next__ and executes to the next yield.
# yield and return are basically the same, but yield is only responsible for returning, not ending the function
# return End Function
(3) Function of generator: Save Memory
(4) difference between send and yield: Send passes a value to the previous yield position. But __next__ can't. You can't send a value to the last yield.
(5) Send () must use __next__ for the first time (because there is no yield on it.)
def func ():
print ("Want to Eat")
A=yield "want to eat spicy soup"
print ("Want to Eat" +a)
B=yield "What else would you like to eat?"
print ("Want to Eat" +b)
C=yield "Sip and sip"
print (c)
Gen=func ()
ret=gen.__next__ ()
print (ret)
ret1=gen.send ("spicy crayfish")
print (RET1)
ret2=gen.send ("sea fishing")
print (Ret2)
Python Full Stack development * 13 Knowledge Point Summary * 180619