[CHAPTER 14] Python iterator

First, iterators

Iteration is a way to access the collection elements. Iterator can remember the object is a traverse position. Iterator object began a visit from the first element of the collection until all the elements are accessed session is over. Iterator can only move forward not backward.

1.1 determine whether an object is an iterative

Can use the isinstance () determines whether an object is an object Iterable:
In [50]: from collections import Iterable

In [51]: isinstance([], Iterable)
Out[51]: True

In [52]: isinstance({}, Iterable)
Out[52]: True

In [53]: isinstance('abc', Iterable)
Out[53]: True

In [54]: isinstance(mylist, Iterable)
Out[54]: False

In [55]: isinstance(100, Iterable)
Out[55]: False

1.2 iterables nature

Our analysis of the object can be an iterative process of iteration and found that for each iteration (ie for ... in ... in every cycle) will return the next data object has been read back data until the iterator All data after the end. Well, in this process, there should be a "person" to record each visit to the first few data for each iteration to return the next data. We put this data to help us perform iterations of "people" called iterator (Iterator).
 
Iterables essence is that we can provide to us in the middle of such a "man" that help us traverse iterator use its iteration.
 
Iterables __iter__ method provided by an iterator to us, when we iteration of an iterative object, in fact, is to first get the object provides an iterator, and get turn by each of the objects of this iterator a data.
 
So in other words, a method has the __iter__ object is a iterables
 1 from collections import Iterable
 2 
 3 
 4 class MyList(object):
 5 
 6     def __init__(self):
 7         self.container = []
 8 
 9     def add(self, item):
10         self.container.append(item)
11 
12     def __iter__(self):
13         """返回一个迭代器"""
14         pass
15 
16 
17 mylist = MyList()
18 print(isinstance(mylist, Iterable))     # True

This time, the test found that adding a __iter__ method mylist object has an iterable the

1.3 iter () function and next () function

list, tuple, etc. are iterables, we can get these functions iterables iterator by iter (). Then we can continue to use the next () function to get the iterator to get the next piece of data. iter () function is actually called __iter__ iterative methods object.
>>> li = [11, 22, 33, 44, 55]
>>> li_iter = iter(li)
>>> next(li_iter)
11
>>> next(li_iter)
22
>>> next(li_iter)
33
>>> next(li_iter)
44
>>> next(li_iter)
55
>>> next(li_iter)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>

Note that when we have finished the last iteration of a data call again next () function will throw StopIteration exception, to tell us all the data has been iteration is complete, you do not have to perform the next () function of.

1.4 How to determine whether an object is an iterator

Can use the isinstance () determines whether an object is an object Iterator:

In [56]: from collections import Iterator

In [57]: isinstance([], Iterator)
Out[57]: False

In [58]: isinstance(iter([]), Iterator)
Out[58]: True

In [59]: isinstance(iter("abc"), Iterator)
Out[59]: True

1.5 Iterator iterator

Through the above analysis, we already know that the iterator is used to help us record the location of each iteration access to, and when we use the next iterator () function returns the next iteration will record its position to us a data location. In fact, when using the next () function call is __next__ method iterator object (Python3 is __next__ method of the object, Python2 is next () method of the object). So, we want to construct an iterator, it is necessary to achieve its __next__ method. But this is not enough, python requires the iterator itself can be iterative, so we have to realize __iter__ method iterator, but __iter__ method to return an iterator, iterator itself it is an iterator, the iteration __iter__ method's return to itself.
 
An object that implements methods and __next__ __iter__ methods, iterators.
1  # achieve iterator (writing two classes) 
2  class of MyList (Object):
 . 3      "" " 
. 4      a custom iterable
 . 5      " "" 
. 6  
. 7      DEF  the __init__ (Self):
 . 8          self.items = []
 . 9  
10      DEF the Add (Self, Val):
 . 11          self.items.append (Val)
 12 is  
13 is      DEF  the __iter__ (Self):
 14          myiterator = myIterator (Self)
 15  
16          return myiterator
 . 17  
18 is  
. 19  class myIterator (Object):
20      "" " 
21          an iterator for the above-defined objects may be used iteration
 22 is      " "" 
23 is      DEF  the __init__ (Self, mylist):
 24          self.mylist = mylist
 25          # Current for the current access to the recording position 
26 is          Self = .current 0
 27  
28      DEF  __next__ (Self):
 29          IF self.current < len (self.mylist.items):
 30              Item = self.mylist.items [self.current]
 31 is              self.current. 1 = +
 32              return Item
 33 is          the else :
 34 is             raise StopIteration
35 
36     def __iter__(self):
37         return self
38 
39 
40 if __name__ == '__main__':
41     mylist = MyList()
42     mylist.add(1)
43     mylist.add(2)
44     mylist.add(3)
45     mylist.add(4)
46     mylist.add(5)
47     for num in mylist:
48         print(num)
1  implemented iterator (written in a category) 
 2  class of MyList (Object):
 . 3  
. 4  
. 5      DEF  the __init__ (Self):
 . 6          self.container = []
 . 7          self.current = 0
 . 8  
. 9  
10      DEF the Add (Self, Item):
 . 11          self.container.append (Item)
 12 is  
13 is  
14      DEF  the __iter__ (Self):
 15  
16  
. 17          return Self
 18 is  
. 19  
20 is      DEF  __next__ (Self):
 21 is          IF self.current < len(self.container):
22             item = self.container[self.current]
23             self.current += 1
24             return item
25         else:
26             raise StopIteration
27 
28 
29 
30 
31 my_list = MyList()
32 my_list.add(1)
33 my_list.add(2)
34 my_list.add(3)
35 my_list.add(4)
36 my_list.add(5)
37 
38 
39 for num in my_list:
40     print(num)

1.6 for ... in ... the cycle of nature

for item in Iterable cycle of nature is the first by iter () function to get iterables iterator Iterable, then get to the iterator continue to call next () method to get the next value and assigned to the item, when the case of StopIteration exception to the end of the cycle.
 
Iterator features:
  • Save memory
  • Inert mechanism
  • It can not be repeated, only down

1.7 application scenarios iterator

Fibonacci number

. 1  class FibIterator (Object):
 2      "" " 
. 3          that the number of conveyance Fibonacci columns
 . 4      " "" 
. 5  
. 6      DEF  the __init__ (Self, n-):
 . 7          "" " 
. 8          : int number indicating the generated series of front n: param n
 . 9          "" " 
10          self.n = n-
 . 11          # current to save the current generated in the first few columns of numbers 
12 is          self.current = 0
 13 is          # num1 used to store a number before before, the initial value of the number of columns the first number 0 
14          self.num1 = 0
 15          # num2 before storage to a number, the second number is the initial value of the number of columns. 1 
16          Self.
num2 = 1 17 
18 is      DEF  __next__ (Self):
 . 19          "" " 
20 is          the next () function call to get the next number of
 21 is          : return:
 22 is          " "" 
23 is  
24          IF self.current < self.n:
 25              NUM = self.num1
 26 is              Self .num1, self.num2 = self.num2, self.num1 + self.num2
 27              self.current. 1 = +
 28              return NUM
 29          the else :
 30              The raise the StopIteration
 31 is  
32      DEF  the __iter__ (Self):
 33 is          "" "
34          "iterator returns itself to __iter__
 35          : return:
 36          " "" 
37 [          return Self
 38 is  
39  
40  IF  the __name__ == ' __main__ ' :
 41 is      FIB = FibIterator (10 )
 42 is      for NUM in FIB:
 43 is          Print ( NUM, End = "  " )

Except for loop can receive iterables, list, tuple, etc. can be received.

1  except for the cycle to receive iterables, list, tuple, etc. can be received.
2  
. 3 Li = List (FibIterator (15 ))
 . 4  Print (Li)
 . 5 TP = tuple (FibIterator (. 6 ))
 . 6  Print (TP)

 

Guess you like

Origin www.cnblogs.com/fengyuhao/p/11541630.html