Iterators
Iteration is one of the most powerful features of Python and is a way to access the elements of a collection.
An iterator is an object that remembers where to traverse.
The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.
Iterators have two basic methods:iter () and next ().
A string, list, or tuple object can be used to create an iterator:
Instance (Python 3.0+)
#print# The next element of the output iterator 1print# The next element of the output iterator 2
An iterator object can be traversed using a regular for statement:
Instance (Python 3.0+)
# for in print (X, end= "")
Execute the above procedure, the output result is as follows:
1234
You can also use the next () function:
Instance (Python 3.0+)
# #while True: try: Print (Next (IT)) except stopiteration: sys.exit ()
Execute the above procedure, the output result is as follows:
1234
Generator
In Python, a function that uses yield is called a generator (generator).
Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator.
In the process of calling the generator to run, the function pauses and saves all current run information each time the yield is encountered, returning the value of yield. and continue running from the current location the next time the next () method is executed.
The following example uses yield to implement the Fibonacci sequence:
Instance (Python 3.0+)
#!/usr/bin/python3ImportSYSdefFibonacci (N):#Generator Function-FibonacciA, b, counter = 0, 1, 0 whileTrue:if(Counter >N):return
yieldA A, b= B, A + b
Counter + = 1F= Fibonacci (10)#F is an iterator that is returned by the generator whileTrue:Try: Print(Next (f), end=" ") exceptStopIteration:sys.exit ()
Execute the above procedure, the output result is as follows:
0112358
Python_ iterators and generators