Iterators
Iterators are a way to access the elements of a collection. 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 going backwards, but that's fine, because people seldom retreat in the middle of an iteration. In addition, one of the great advantages of iterators is that they do not require that all elements in the entire iteration be prepared in advance. An iterator computes an element only when it iterates over it, and before or after that, the element may not exist or be destroyed. This feature makes it ideal for traversing large or infinite collections, such as several G files.
Characteristics:
- The visitor does not need to care about the structure inside the iterator, but only needs to go through __next () __ (python2.x for Next ()) method to fetch the next content continuously.
- A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end, that is, it cannot be taken anywhere, like a list, by subscript, and is generally used for loop traversal
- You can't go back halfway through the interview.
- Facilitates recycling of large data sets, saving memory
python built-in functions ITER is a simple built-in function that helps us create an iterator.
>>> it = iter ([1, 2, 3, 4]) # Built-in functions ITER and the list generates an iterator >>> It <list_iterator object at 0x7faa075f4ef0>>>> it. __next__ () # get a value by __next method >>> it.< Span style= "color: #800080;" >__next__ >>> it. __next__ () # The iterator has only 4 elements, and if you continue using the next method at this point, you will get an error Span style= "color: #000000;" >traceback (most recent): File , Line 1, in < Module>stopiteration
In fact, we rarely use the __next__ () method to take a single value, and in most cases we use a for-in loop to iterate.
>>> it = iter ([1, 2, 3, 4]) for in it: ... Print 24
Generator
The generator is a function call that returns an iterator, which is called the generator. Plainly, the generator generates iterators. The difference from a normal function is that the yield keyword
We use the Fibonacci sequence to illustrate the difference between a generator and a normal function.
Common function implementation
def fib (max): = 0, 0, 1 = [] while n < Max: res.append (b) = B, a + b = n + 1 return= fib (6)print(res) for inch Res: Print (i) results of implementation [1, 1, 2, 3, 5, 8]138
Generator
def fib2 (max): = 0, 0, 1 while n < Max: yield b = b, A + b = n + 1
print
(res)
for in
Res:
print
(i) execution result
#
You can see that a generator object is returned, and that something inside the generator is not executed immediately, but instead returns an iterator when it executes to yield 138
Python route sixth: Python Basics (22)-Generators and iterators