Python iterator and generator instance details, python Generator

Source: Internet
Author: User

Python iterator and generator instance details, python Generator

This article describes the python iterator and generator with examples, as shown below:

1. iterator Overview:
 
An iterator is a way to access collection elements. 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, but there is nothing to do with it, because people seldom go back on the way of iteration.
 
1.1 advantages of using the iterator
 
For data structures (such as tuple and list) that support random access in the native, The iterator has no advantage over index access in the classic for loop, instead, the index value is lost (you can use the built-in function enumerate () to retrieve the index value ). However, for data structures (such as set) that cannot be accessed randomly, the iterator is the only way to access elements.

In addition, the major advantage of the iterator is that it is not required to prepare all elements in the entire iteration process in advance. The iterator calculates an element only when it iterates to an element. Before or after this, the element may not exist or be destroyed. This feature makes it especially suitable for Traversing large or infinite sets, such as several G files or Fibonacci series.

The primary benefit of the iterator is that it provides a unified interface for accessing the set. As long as the _ iter _ () method object is defined, the iterator can be used for access.
 
The iterator has two basic methods:
 
Next method: return the next element of the iterator.
_ Iter _ method: return the iterator object itself
The following uses the generation of the Fibonacci series as an example to explain why the iterator is used.
 
Sample Code 1

 def fab(max):   n, a, b = 0, 0, 1   while n < max:     print b     a, b = b, a + b     n = n + 1

Print directly in the function fab (max) will lead to poor reusability of the function, because fab returns None. Other functions cannot obtain the series returned by the fab function.
 
Sample Code 2

 def fab(max):   L = []  n, a, b = 0, 0, 1   while n < max:     L.append(b)     a, b = b, a + b     n = n + 1  return L

Code 2 meets the reusability needs, but occupies the memory space, it is best not.
 
Sample Code 3
 
Comparison:
 

for i in range(1000): passfor i in xrange(1000): pass

The first one returns a list of 1000 elements, and the last one returns an element in each iteration. Therefore, the iterator can be used to solve the problem of Space reuse.
 

 class Fab(object):   def __init__(self, max):     self.max = max     self.n, self.a, self.b = 0, 0, 1    def __iter__(self):     return self    def next(self):     if self.n < self.max:       r = self.b       self.a, self.b = self.b, self.a + self.b       self.n = self.n + 1       return r     raise StopIteration()

Run

>>> for key in Fabs(5):  print key

The Fabs class continuously returns the next number of columns through next (), and the memory usage is always constant.

1.2 use iterator

You can use the built-in factory function iter (iterable) to obtain the iterator object:

>>> lst = range(5)>>> it = iter(lst)>>> it<listiterator object at 0x01A63110>

You can use the next () method to access the next element:

>>> it.next() >>> it.next() >>> it.next()

When python processes the iterator out of bounds, it throws a StopIteration exception.

>>> it.next() >>> it.next<method-wrapper 'next' of listiterator object at 0x01A63110>>>> it.next() >>> it.next() Traceback (most recent call last): File "<pyshell#27>", line 1, in <module>  it.next()StopIteration

After learning about StopIteration, you can use the iterator to traverse it.

lst = range(5)it = iter(lst)try:  while True:    val = it.next()    print valexcept StopIteration:  pass

In fact, because the iterator is so common, python specifically makes the iterator syntax sugar for the for keyword. In the for loop, Python will automatically call the factory function iter () to obtain the iterator, call next () to obtain the element, and check for StopIteration exceptions. As follows:

>>> a = (1, 2, 3, 4)>>> for key in a:  print key

First, python calls the iter function iterator for the object after the keyword in, and then calls the next method of the iterator to obtain the element until a StopIteration exception is thrown.

1.3 define iterator
 
The following example is the Fibonacci series.
 

#-*-Coding: cp936-*-class Fabs (object): def _ init _ (self, max): self. max = max self. n, self. a, self. B = 0, 0, 1 # Special Note: 0th items are 0, 1st items are the first 1. the entire series starts from 1 def _ iter _ (self): return self def next (self): if self. n <self. max: r = self. B self. a, self. B = self. b, self. a + self. B self. n = self. n + 1 return r raise StopIteration () print Fabs (5) for key in Fabs (5): print key

Result

<__main__.Fabs object at 0x01A63090>

2. iterator

A function with yield is called a generator (generator) in Python. Several examples are provided to illustrate this problem)
 
It can be seen that code 3 is far from code 1 concise. The generator (yield) can maintain the simplicity of code 1 and the effect of code 3.
 
Sample Code 4
 

def fab(max):  n, a, b = 0, 0, 1  while n < max:    yield b    a, b = b, a + b    n = n = 1

Run

>>> for n in fab(5):  print n

In short, yield is used to convert a function into a generator. A function with yield is no longer a common function. The Python interpreter regards it as a generator and calls fab (5) instead of executing the fab function, an iterable object is returned! During for loop execution, code in the fab function is executed in each loop. When yield B is executed, the fab function returns an iteration value. During the next iteration, the Code continues to run from the next statement of yield B, and the local variable of the function looks exactly the same as before the last interrupted execution, so the function continues to run until yield is encountered again. It seems that a function is interrupted several times by yield during normal execution, and the current iteration value is returned through yield for each interruption.
 
You can also manually call the next () method of fab (5) (because fab (5) is a generator object and this object has the next () method ), in this way, we can see the fab execution process more clearly:

>>> f = fab(3)>>> f.next()1>>> f.next()1>>> f.next()2>>> f.next() Traceback (most recent call last): File "<pyshell#62>", line 1, in <module>  f.next()StopIteration

Return Function

In a generator, if there is no return, the function is executed by default. If return is encountered, if return is executed, the StopIteration is directly thrown to terminate the iteration. For example
 

>>> s = fab(5)>>> s.next()1>>> s.next() Traceback (most recent call last): File "<pyshell#66>", line 1, in <module>  s.next()StopIteration

Sample Code 5 File Reading

 def read_file(fpath):   BLOCK_SIZE = 1024   with open(fpath, 'rb') as f:     while True:       block = f.read(BLOCK_SIZE)       if block:         yield block       else:         return

If you call the read () method directly on a file object, unpredictable memory usage may occur. A good way is to use a fixed-length buffer to constantly read the file content. With yield, you can easily read files without having to write iteration classes for reading files.


How to Use the iterator in python?

List = [1, 2, 3, 4, 5, 6]
For item in list:
Print item

How to Use the iterator in python? For example,

Are you talking about enumerate?

The simplest example is as follows:
ListValue = ["a", "B", "c"]
For index, strValue in enumerate (listValue ):
Print index, "is", strValue

The result is:
0 is
1 is B
2 is c
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.