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