Python15: iterators and generators

Source: Internet
Author: User

Iterators and generators are powerful tools provided by Python to help users write elegant code. The following describes how iterators and generators are used and the internal mechanisms.

Iterators

In Pyton, most container objects can be used in a For loop:

for element in [1, 2, 3]:    print (Element) for element in (1, 2, 3):    print (Element) for key in {' One ': 1, ' both ': 2}:
   
    print (key) for Char in "123":    print (char) for line in open ("MyFile.txt"):    print (line, end= ")
   
Such access is very convenient and the use of iterators throughout Python. In the For statement, first calls the container's ITER () method to get the container's iterator, Python requires that the iterator defines the method __next__ (), which acquires a container's data once, and when the container has no more data, __next__ () Throws a stopiteration exception to tell the For loop to end. You can use the built-in function next () to call the __next__ () method, and here's an example:

>>> s = ' abc ' >>> it = iter (s) >>> It<iterator object at 0x00a1db50>>>> next (it) ' A ' >>> next (it) ' B ' >>> next (IT) ' C ' >>> next (IT) Traceback (most recent):  File " <stdin> ", line 1, in?    Next (IT) stopiteration
By understanding the mechanisms behind the iterators, it is easy to add iterator behavior to your class. You only need to define a __iter__ () method to return an object that implements the __next__ () method, and if the class defines the __next__ () method, then __iter__ () returns self:

Class Reverse: "" "    Iterator for looping over a sequence backwards.    " "" " def __init__ (self, data):        self.data = data        Self.index = Len (data)    def __iter__ (self):        return    Self def __next__ (self):        if Self.index = = 0:            raise stopiteration        self.index = self.index-1        return Self.data[self.index]>>> rev = Reverse (' spam ') >>> iter (rev) <__main__. Reverse object at 0x00a1db50>>>> for char in Rev: ...     Print (char) ... maps
Why use iterators instead of lists? The main reason is that the list consumes too much memory. Iterators allow you to calculate one value at a time instead of getting all the values through the list at a time, and using iterators can be more general, simpler, and more elegant.

Generator

The generator is used to create iterators, which, like normal functions, use the yield statement in addition to returning data. Each time next () is called, the generator restarts from where it was stopped (it remembers all the data values and the last executed statement). The following is an example of a generator:

DEF reverse (data):    for index in range (LEN (data)-1,-1,-1):        yield data[index]>>> for char in reverse (' Go LF '): ...     Print (char) ... flog
Anything that can be done by the generator can be done using iterators, and the generators can be so concise because the __iter__ () and __next__ () methods are automatically generated.
Another benefit of the generator is that local variables and execution descriptions are automatically saved between two calls, so the generator is easier to write and clearer than using that instance variable.
Outside of the auto-generate method and save state, when the generator aborts, they automatically throw stopiteration.
In general, these features make it easier to use the generator.

Generator expression

Some simple generator can be used to describe the expression as a generator expression. The generator expression is more concise. Take a look at some of the following examples:

>>> sum (i*i for I in range)                 # sum of squares285>>> Xvec = [Ten, 30]>>> Yvec = [7, 5, 3]>>> sum (x*y for x, y in Zip (Xvec, Yvec))         # dot product260>>> from Math import pi, sin>>> Sine_table = {X:sin (x*pi/180) for X in range (0, $)}>>> unique_words = set (word for line in  page for  wor  D in Line.split ()) >>> valedictorian = Max ((Student.gpa, student.name) for student in graduates) >>> data = ' Golf ' >>> list (data[i] for I in range (len (data)-1,-1,-1)) [' F ', ' l ', ' o ', ' G ']

Python15: iterators and generators

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.