Python iterators: iter () and __iter__ ()

Source: Internet
Author: User

Overview

The greater credit for iterators is the interface that provides a unified access to the collection. Iterators provide an interface for class sequence objects with a sequence of classes . 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 backing back . Python's iterations seamlessly support sequence objects, and it also allows programmers to iterate over non-sequential types, including user-defined objects. Iterators are handy, you can iterate over objects that are not sequences but exhibit sequence behavior , such as dictionary keys, rows of a file, and so on.

Essentially, an iterator is an object that has a next () method , rather than counting by index.

The role of iterators is as follows:

提供了可扩展的迭代器接口;对列表迭代带来了性能上的增强;在字典迭代中性能提升;创建真正的迭代接口,而不是原来的随即对象访问;与所有已经存在的用户定义的类以及扩展得模拟序列和映射的对象向后兼容;迭代非序列集合(例如映射和文件)时,可以创建更简洁可读的代码

How to create an iterator

1. Call the ITER () function

A call to ITER () on an object can get his iterator. Examples are as follows:

#! /usr/bin/env python#coding =utf-8DefIter_test(): i = iter (' Happy ')#!!!try: while True: print i.next () except stopiteration: pass s = { Span class= "hljs-string" > ' one ': 1, ' ": 2, ' three ': 3} print s M = iter (s) #!!! try: while True: print m.next ()  #s [M.next ()] except Stopiteration: passif __name__ = =  ' __main__ ': iter_test ()              

Results:

happy{‘three‘: 3, ‘two‘: 2, ‘one‘: 1}threetwoone

2, using the class implementation __iter__() and next() functions

Another way to create an iterator is to use a class, a class that implements a __iter__()和next() method that can be used as an iterator.

next方法:返回迭代器的下一个元素__iter__方法:返回迭代器对象本身

Take the Fibonacci sequence as an example, with the following code:

#! /usr/bin/env python#coding =utf-8ClassHi(object):Def__init__(self): SELF.A, self.b =0,1# Initialize two counters A/bdef __iter__ return" # instance itself is an iterative object, So return to yourself def next # calculate next value if self.a > 10: # conditions for exiting the loop raise stopiteration (); return self.a # return next value if __name__ = =  ' __main__ ': for n in Fib (): print n            

Results:

112358

Python iterators: iter () and __iter__ ()

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.