Using Python iterator

First look iterables

Speaking of iterators must first mention iterables (iterable), iterables is able to target its members one by one to return the item. Iterables comprises a sequence type (e.g., list, str, tuple) and a non-sequence types (e.g. dict, file object defined __iter__()method, or the Sequencesemantics of __getitem__()any custom class object's method.). An iteration object has a __iter__()method, which means that there is __iter__()a method object is iterable.

Iterator

In Python, the iterator is to follow an iterative protocol object used to represent a series of data streams. Repeat call the iterator __next__()method (or pass it to the built-in function Next ()) returns one by one item in the data stream. When there is no data available will throw StopIterationan exception.

Iterator divided into two categories:

  • Use iter()obtained iterator (e.g., list, tuple, dict, set, etc.) from any sequence objects.
  • Input iterator generator(Builder comprises a belt and a yieldfunction).

Iterator There are two basic methods:

  • iter() Returns an iterator object
  • next() Return items one by one iteration object

Use iterator

Use iter () returns an iterator

In [1]: list = ['A', 'B', 'C']

In [2]: iters = iter(list)

In [3]: print(next(iters))
A

In [4]: print(next(iters))
B

In [5]: print(next(iters))
C

In [6]: print(next(iters))
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-6-9689206231f0> in <module>
----> 1 print(next(iters))

StopIteration:

list is a list of length 3, use the list as a parameter can be returned iterator iterations only three items, when the range exceeds an iteration throws StopIterationan exception.

Use for traversal iterator

Iterator object can be used for statement to traverse.

list = ['A', 'B', 'C']
iters = iter(list)
for i in iters:
  print(i)

Output:

A
B
C

File iteration

Read the contents of a text file line by line

for i in open("test.txt", encoding="utf-8"):
	print(i)

Custom iterator

By implementing a class __iter__()and __next__()to create an iterator method.

Iterator must have __iter__()a method that returns the iterator object itself.

class MyIter:

    def __init__(self, m):
        self.data = m
        self.length = len(m)
        self.index = -1

    def __iter__(self):
        return self
  
    def __next__(self):
        if self.index < self.length-1:
            self.index += 1
    else:
        raise StopIteration 
    return self.data[self.index]
  
# def next(self): # Python2 中使用next()
#     if self.index < self.length-1:
#         self.index += 1
#     else:
#         raise StopIteration 
#     return self.data[self.index]

iters = MyIter(['A', 'B', 'C'])
for i in iters:
    print(i)
# print(next(iters))
# print(next(iters))
# print(next(iters))
Published 33 original articles · won praise 62 · views 240 000 +

Guess you like

Origin blog.csdn.net/Jairoguo/article/details/104483824