- Iteration is one of the most powerful functions of python and a way to access collection elements
- An iteration is an object that can remember the traversal position
- The object of the iterator is accessed from the first object of the collection until the access is over, and the iterator only moves forward
- The basic methods of iterators: iter() and next()
The essence of an iteratable object is that it can provide us with such an intermediate "person", that is, an iterator, to help us iterate over it.
Iteratable object passing__ iter__ Method provides us with an iterator. When we iterate over an iteratable object, we actually get an iterator provided by the object first
After that, each data in the object is obtained in turn through this iterator.
list = [1, 2, 3, 4, 5] # Create list l = iter(list) # Create iterator print(next(l)) # Output element (first) one print(next(l)) # Output element (second) two print(next(l)) # Output element (third) three
The iterator can also use the for loop to iterate and output all elements
list = [1, 2, 3, 4, 5] # Create list l = iter(list) # Create iterator for i in l: # Loop traversal print(i, end=' ') # Output the data after the cycle, end station space # Results: 1 2 3 4 5 # next function list = [1, 2, 3, 4, 5] # Definition list l = iter(list) # Create iterator while True: # Infinite loop try: # judge print(next(l)) # output except StopIteration: # Prevent error StopIteration sys.exit() # Results: 1 2 3 4 5
- To create an iterator, you need to use it in your class__ iter__ () and__ nect__ () method. Note: two_
- init() method: returns a special iterator object, which is called__ next()__ Method, and it is completed through the stop exception prompt
- next() method: returns the next iterator object
class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x myclass = MyNumbers() myiter = iter(myclass) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) # Results: 1 2 3 4
The StopIteration exception is used to identify the completion of the iteration and prevent infinite loops. In the next() method, we can set the StopIteration exception to be triggered after completing the specified number of cycles to end the iteration.
class MyNumbers: # Define function def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 6: # Define the number of cycles x = self.a self.a += 1 return x else: raise StopIteration # Report and return myclass = MyNumbers() # Transfer function value myiter = iter(myclass) # Define iterators for x in myiter: # Loop through and output print(x) # Results: 1 2 3 4 5 6
- python uses the yield method to define the generator, which can only be used for iterative operation, that is, to generate an iterator
- When running the generator, the yield function will pause and save the current information, and continue to run from the current position the next time the next() method is executed.
# Generate Fibonacci sequence import sys # Import sys def fibonacci(n): # Generator function - Fibonacci a, b, counter = 0, 1, 0 # Definition number while True: # Infinite loop if (counter > n): # Circular judgment return # Return null yield a # generator a, b = b, a + b # definition counter += 1 # Self increasing f = fibonacci(10) # f is an iterator that is returned by the generator while True:# Infinite loop try: # No error message print(next(f), end=" ") # Output results except StopIteration: # r to report StopIteration error sys.exit()