Iteratable object is a term we are very familiar with. We have also briefly introduced the iteratable object that can be looped for, but in fact, the water in it is deeper.
The relationship between iterator and for loop
-
Iterator protocol:
The object must conform to a next method. Executing the method either returns the next item in the iteration or causes a StopIteration exception to terminate the iteration (only backward, not forward) -
Iteratable objects:
Objects that implement the iterator protocol -
The essence of for loop:
First, change the object into an iterative object, recycle all objects, and use the iterator protocol. You have to call the next method in the protocol once
Be careful:
String, list, tuple, dictionary, collection and file objects are not iteratable objects. They do not have next methods at all. However, in the for loop, they call their internal "iterator" method to make them iteratable objects -
Powerful for loop mechanism:
Based on the iterator protocol, it provides a unified method to traverse all objects. No matter it is an ordered list, string, tuple, or an unordered collection, dictionary, or file, it can be traversed through the for loop -
How the iterator works:
x = 'world' iter_test=x.__iter__() #Use 'iter' to make an x string an iteratable object print(iter_test) #This will print out the code of the iteratable object #After becoming an iteratable object, there is a next method specific to the iteratable object, which can be operated step by step print(iter_test.__next__()) print(iter_test.__next__()) print(iter_test.__next__()) print(iter_test.__next__()) print(iter_test.__next__())
Operation result:
w
o
r
l
d
Output all the characters in the string one by one
- while loop simulates the combination of for loop and iterator:
x = 'world' iter_x = x.__iter__() #Make a string an iteratable object while True: #Loop iterated object try: print(iter_x.__next__()) #Output the result of each traversal except StopIteration: #If StopIteration occurs, terminate print('The iteration is over. The cycle is over') break
Operation result:
w
o
r
l
d
The iteration is over. The cycle is over
- The value of the built-in function next() can be used to iterate over the object:
x = ['may','you','be','happy'] iter_x=x.__iter__() #Use 'iter' to make an x string an iteratable object #Using the built-in function next() to take the value of an iterative object print(next(iter_x)) print(next(iter_x)) print(next(iter_x)) print(next(iter_x))
Operation result:
may
you
be
happy
generator
-
From the above analysis, we can see that the object following the iterator protocol is the iteratable object, which is the iterator
-
Generator: a data type that automatically implements an iterative protocol. By default, this type of data has already been iter, so there is a "next" method by default
-
Generator function:
The return value of the function uses yield instead of return, so the returned data is a generator. The default iteratable object has the next method
def test(): yield 'ok' res = test() print(res) print(next(res))
Ternary expression
name = 'Wu Thorpe' res = 'Liar' if name == 'Wu Thorpe' else 'Brave marine Warrior' #Ternary expression, put the expression to be executed when if is True before if, followed by else #If the value of the name variable is' usop ', assign' cheat 'to res, #Otherwise it's assigned as' brave marine Warrior ' print(res)
Operation result:
Liar
List parsing and builder expression
- Normal assignment:
egg = [] for i in range(10): egg.append('Egg%s'%i) print(egg)
Operation result:
['egg 0 ',' egg 1 ',' egg 2 ',' egg 3 ',' egg 4 ',' egg 5 ',' egg 6 ',' egg 7 ',' egg 8 ',' egg 9 ']
- List resolution (fast assignment):
egg = [] egg = ['Egg%s'%i for i in range(10)] print(egg)
You can even do this:
egg = [] egg = ['Egg%s'%i for i in range(10) if i>=5] #A ternary expression print(egg)
But pay attention. There is no quaternion expression, all cannot:
egg = ['Egg%s'%i for i in range(10) if i>=5 else i]
- Builder expression:
chicken = ('chicken%s' %i for i in range(10)) #Make a generator print(chicken) #Output generator, which shows that it is an iterative object print(chicken.__next__()) #Use the next method to output iteratable objects one by one print(chicken.__next__()) print(next(chicken)) print(next(chicken))
Operation result:
Chicken 0
Chicken 1
Chicken 2
Chicken 3
Ps: List parsing and generator expression are both convenient programming methods, but generator expression saves more memory, because it is based on one value by one of iterator protocol