Python iter () function usage Example Analysis, pythoniter

Source: Internet
Author: User

Python iter () function usage Example Analysis, pythoniter

This example describes the usage of the Python iter () function. We will share this with you for your reference. The details are as follows:

The iterator in python is very clever to use. It can not only iterate sequences, but also iterate objects that exhibit sequential behavior, such as Dictionary keys, row of a file, and so on.

The iterator hasnext()Instead of counting through indexes. When a loop mechanism is used to require the next item, the next () method of the iterator is called. After iteration, A StopIteration exception is thrown.

However, the iterator can only move backward, cannot return to the start, and can only create another iteration object.

Reverse iteration tool:reversed()Returns an iterator for reverse access. Iteration module provided in python: itertools Module

Let's take a look at several examples:

>>> l=[2,3,4]>>> iterl=iter(l)>>> iterl.next()2>>> iterl.next()3>>> iterl.next()4>>> iterl.next()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration
>>> D = {'one': 1, 'two': 2, 'three ': 3 }>>> d {'three': 3, 'two ': 2, 'one': 1 }>>> iterd = iter (d) # The dictionary iterator traverses the dictionary key >>>> iterd. next () 'Three '>>> iterd. next () 'two' >>> iterd. next () 'one' >>> iterd. next () Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration

The following shows the help information of the iter () function:

>>> help(iter)Help on built-in function iter in module __builtin__:iter(...)  iter(collection) -> iterator  iter(callable, sentinel) -> iterator  Get an iterator from an object. In the first form, the argument must  supply its own iterator, or be a sequence.  In the second form, the callable is called until it returns the sentinel.

iter()A function can be used either by passing a parameter or by passing two parameters. All results return an iterator object.

The so-called iterator object is an object with a next () method. The convention or convention of the next method (convention) is that the next value is returned every time it is executed (therefore, it must record its own status, usually recorded on the iterator object ), until there is no value for raiseStopIteration.

Pass 1 parameter: The collection parameter should be a container that supports the iteration protocol (that is, the definition includes__iter__()Function), or support the sequence Access Protocol (that is, defined__getitem__()Function). Otherwise, a TypeError exception is returned.

Pass two parameters: when the second parameter sentinel appears, the callable parameter should be a callable object (instance), that is, defined__call__()When the enumerated value is equal to the value of the Sentinel, an exception StopIteration is thrown.

>>> S = 'abc' # s supports the sequence access protocol, which has the _ getitem _ () method >>> help (str. _ getitem _) Help on wrapper_descriptor :__ getitem __(...) x. _ getitem _ (y) <==> x [y] >>> s. _ getitem _ (1) 'B'> s [1] 'B'> iters = iter (s) # iters is an iterator object, it has the next () and _ iter _ () Methods >>> iters1 = iters. _ iter _ () >>> iters2 = iter (iters) >>> iters <iterator object at 0x030612D0 >>>> iters1 <iterator object at 0x030612D0 >>>> iters2 <iterator object at 0x030612D0> it Ers iters1 iters2 is the same iterator! >>> Iters. next () 'A' >>> iters. next () 'B'> iters. next () 'C' >>> iters. next () Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
>>> Class test: # The test class supports the iteration protocol because it defines the _ iter _ () function... def _ iter _ (self ):... print '_ iter _ is called! '... Self. result = [1, 2, 3]... return iter (self. result)...> t = test () # t supports iteration protocols> for I in t: # t is called when the for I in t is executed. _ iter _ (), that is, _ iter _ (t), returns an iterator object... print I ,... _ iter _ is called! 1 2 3 >>> for I in t. _ iter _ (): print I ,__ iter _ is called !! 1 2 3 >>> for I in test. _ iter _ (t): print I ,__ iter _ is called !! 1 2 3 >>> l = [, 3] >>> for I in l:... print I,... 1 2 3
# The above for loop actually works like this (The for loop will automatically call the next () method of the iterator), as follows: >>> iterl = iter (l) >>> while True :... try :... I = iterl. next ()... operation t StopIteration :... break... print I ,... 1 2 3
>>> F = open (r 'C: \ Users \ Administrator \ Desktop \ test.txt ', 'w') >>> f. writelines (['Love python \ n', 'Hello python \ n', 'Love python \ n']) >>> f. close () >>> f = open (r 'C: \ Users \ Administrator \ Desktop \ test.txt ', 'R') >>> for line in f: # The iterator generated by the file object will automatically call the readline () method, so that loop traversal can access all rows of the text file... print line [:-1]... love pythonhello pythonlove python

The functions of the for loop are the same as those of the following code:

>>> while True:...   line=f.readline()...   if line!='':...     print line[:-1]...   else:...     break...love pythonhello pythonlove python
>>> f=open(r'C:\Users\91135\Desktop\test.txt','r')>>> f.readlines()['love python\n', 'hello python\n', '\n', 'love python\n']>>> f.seek(0)>>> f.next()'love python\n'>>> f.next()'hello python\n'>>> f.next()'\n'>>> f.next()'love python\n'>>> f.next()Traceback (most recent call last): File "<pyshell#140>", line 1, in <module>  f.next()StopIteration>>> f.seek(0)>>> it1=iter(f)>>> it2=f.__iter__()

F iter1 iter2 is the same object !!!

>>> f<open file 'C:\\Users\\91135\\Desktop\\test.txt', mode 'r' at 0x030E9A70>>>> it1<open file 'C:\\Users\\91135\\Desktop\\test.txt', mode 'r' at 0x030E9A70>>>> it2<open file 'C:\\Users\\91135\\Desktop\\test.txt', mode 'r' at 0x030E9A70>>>> f.next()'love python\n'>>> it1.next()'hello python\n'>>> next(it2)'\n'>>> next(f)'love python\n'>>> next(f)Traceback (most recent call last): File "<pyshell#247>", line 1, in <module>  next(f)StopIteration>>> it1.next()Traceback (most recent call last): File "<pyshell#248>", line 1, in <module>  it1.next()StopIteration>>> it2.next()Traceback (most recent call last): File "<pyshell#249>", line 1, in <module>  it2.next()StopIteration
iter(callable, sentinel) -> iterator

If two parameters are passediter()The first parameter must be callable, which will repeatedly call the first parameter,

Until the next value of the iterator is sentinel: in subsequent iterations, sentinel stops immediately after iteration.

For details about what is callable in Python, refer to: python callable () function

>>> Class IT (object): def _ init _ (self): self. l = [1, 2, 3, 4, 5] self. I = iter (self. l) def _ call _ (self): # instances of classes defining the _ call _ method are callable items = next (self. i) print "_ call _ is called, which wowould return", item return item def _ iter _ (self ): # supports the iteration protocol (defined as the _ iter _ () function) print "_ iter _ is called !! "Return iter (self. l) >>> it = IT () # it is callable >>> it1 = iter (it, 3) # it must be callable, otherwise, callable_iterator >>> callable (it) True >>>> it1 <callable-iterator object at 0x0306DD90 >>> for I in it1: print I _ call _ is called, which wowould return 11 _ call _ is called, which wowould return 22 _ call _ is called, which wowould return 3

We can see that the it1 type obtained by passing in two parameters is callable_iterator, which is called every time it is called.__call__Function, and the final output 3 is stopped.

>>> it2=iter(it)__iter__ is called!!>>> it2<listiterator object at 0x030A1FD0>>>> for i in it2:print i,1 2 3 4 5

Compared with it1, it2 is much simpler. it can return the iterator of a container in its own class.

The above example is just to introduce the function of passing two parameters by iter () function. If you really want to write an iterator class, you also need to define the next function, this function returns a value each time to implement iteration.

>>> class Next():        def __init__(self,data=825):              self.data=data        def __iter__(self):              return self        def next(self):              print "next is called!!"              if self.data>828:                  raise StopIteration              else:                  self.data+=1                  return self.data>>> for i in Next():print inext is called!!826next is called!!827next is called!!828next is called!!829next is called!!>>> for i in Next(826):print inext is called!!827next is called!!828next is called!!829next is called!!>>>

The only thing that needs to be noted is that the end condition of the iterator must be controlled in next. Otherwise, an endless loop will occur.

>>> it=Next()>>> it.__iter__()<__main__.Next instance at 0x02E75F80>>>> Next.__iter__(it)<__main__.Next instance at 0x02E75F80>>>> iter(it)<__main__.Next instance at 0x02E75F80>>>> it<__main__.Next instance at 0x02E75F80>>>> it=Next()>>> it.next()next is called!!826>>> next(it)next is called!!827>>> Next.next(it)next is called!!828>>> next(it)next is called!!829>>> it.next()next is called!!Traceback (most recent call last): File "<pyshell#68>", line 1, in <module>  it.next() File "<pyshell#1>", line 9, in next  raise StopIterationStopIteration

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.