Python Learning notes-iterators

Source: Internet
Author: User

What is an iterator:

 It provides an interface for class sequence objects with a sequence of classes. They are a set of data structures, and you can use their indexes to "iterate" from 0 to the last entry in the sequence.

How to use iterators:

(1) use in the sequence

2, 3)>>>i = iter (mytuple)>>>i.next ()1>>>I.next ()2>>>i.next ()3>>>"", line 6,   <module>     i.next () stopiteration

  (2) Use in dictionaries

The dictionary iterator iterates through its key (key). The statement for Eachkey in Mydict.keys () can be abbreviated to for Eachkey in Mydict

>>>dict1={('Poe','author'):(1809,1849,1976),... ('Gaudi','Architect'):(1852,1906,1987)}>>> forEachdictinchDict1: ...Print 'Name:%s\toccupation:%s'%eachdict ...Print 'Birth:%s\tdeath:%s\t Album:%s\n' ...    %Dict1[eachdict]name:poe occupation:author Birth:1809 death:1849 album:1976Name:gaudi occupation:architect Birth:1852 death:1906 album:1987

In addition, Python introduces three new built-in dictionary methods to define iterations: Mydict.iterkeys () (by key iteration), Mydict.itervalues () (by value iteration), and Mydict.iteritems () (Iterative by key-value pairs).

  (3) use in the file

The iterator generated by the file object automatically calls the ReadLine () method. This allows the loop to access all lines of the text file.

>>>myfile = open ('c:\\users\\tyy\\desktop\\xxx.txt')>>>  for inch myFile:            Print EACHLINE,AAAABBBBCCCC>>>myfile.close ()

3. How to create an iterator

  Call ITER () on an object to get its iterator. Its syntax is as follows:

ITER (obj)

ITER (func, Sentinel)

If you pass a value to ITER (), it will check whether you are passing a sequence, if it is, then iterate from 0 to the end of the sequence according to the index.

If you pass two values to ITER (), it will call Func repeatedly until the next value of the iterator equals Sentinel.

Python Learning notes-iterators

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.