Python3 iterator and generator, python3 Generator
Pythom3 iterator and Generator
Iterator
'''
The iterator is one of the most powerful functions of python and a way to access collection elements.
The iterator is a location object that can remember to traverse
The iterator object is accessed from the first element of the set until all elements are accessed. The iterator can only move forward without moving back.
The iterator has two basic methods: iter () and next ().
String, list, or tuples can be used to create an iterator:
'''
List = [1, 2, 6, 3] it = iter (list) # create an iterator object print (next (it) # result 1 print (next (it )) # result 2 print (next (it) # result 6 # Based on the above, we can infer that the next element of the iterator can be output once printed. for I in it: # Use the for loop to iteratively output print (I) # You can also use the next () function import sys # introduce sys module li = [1, 2,] ip = iter (li) # create an iterator object while True: try: print (next (ip) before t StopIteration: sys. exit () # result 1, 2
Generator yield
'''
In python, functions using yield are called generators)
Unlike normal functions, a generator is a function that returns an iterator and can only be used for iterative operations. To put it simply, a generator is an iterator.
During the running of the generator, the function will pause and save all running information each time yield is encountered, and the yield value will be returned.
And continue running from the current position when the next () method is executed.
'''
# Use yield to implement the fibonacci sequence import sysdef fibonacci (n): # generate the function fibonacci a, B, counter = 0, 0 print ('A', a) while True: if (counter> n): return yield a, B = B, a + B counter + = 1f = fibonacci (10) # f is an iterator generated by the generator while True: try: print (next (f), end = '') Stopping t StopIteration: sys. exit () # The result is, 55.
Summary;
When to use yield
A function f and f return a list, which is dynamically calculated (whether calculated in mathematics or formatted in logic ),
In addition, this list will be large (whether it is fixed or increased with the increase of input parameters). At this time, we hope to call this function each time and use the iterator
In the loop, each list element is obtained one by one instead of a complete list to save memory. yield is useful in this case.