Python iterators and generators

Source: Internet
Author: User

Always thought that Python generator is a list generation, OK, I read less.

In fact, the generator is the generator object that implements the iterator protocol using yield returns. As follows:

Class Data (object):    def __init__ (self, *args):        self._data = list (args)    def __iter__ (self): for        x in Self._data:            yield x    d = data ()    >>> d.__iter__ ()    <generator object __iter__ at 0x7f8556d4cdc8>

Use D.next () in Python2 to return the next value of D,
In Python3, you need to use Dnext() to return the next value of the generator for D, which can be used for the process to be built.

About Iterators
Depending on the iterator protocol, both ITER() and Next () Two methods need to be implemented, which returns an Iterator object, which returns data until the end of the stopiteration exception is thrown.

Class Data (object):d EF __init__ (Self, *args):    self.data = list (args)    Self.index = 0def __iter__ (self):    return selfdef __next__ (self):    if Self.index < Len (self.data):        d =  Self.data[self.index]        Self.index +=1    Else:        raise Stopiteration ()    return D

Python iterators and generators

Related Article

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.