[python] Advanced Programming Skills (2) Iterator

Insert picture description here
Iteration is one of Python's most powerful features, and it is a way to access collection elements.

An iterator is an object that can remember the position of the traversal.

The iterator object is accessed from the first element of the collection until all the elements have been accessed. The iterator can only go forward and not go backward.

There are two basic methods for iterators: iter() and next().

String, list or tuple objects can all be used to create iterators:

list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
print (next(it))   # 输出迭代器的下一个元素

print (next(it))

next(*)

import sys         # 引入 sys 模块
 
list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
 
while True:
    try:
        print (next(it))
    except StopIteration:
        sys.exit()

Using a class as an iterator requires implementing two methods in the class, iter () and next ().

If you already know object-oriented programming, you know that a class has a constructor. Python's constructor is init (), which will be executed when the object is initialized.

Read more: Python3 object-oriented

The iter () method returns a special iterator object, which implements the next () method and identifies the completion of the iteration through the StopIteration exception.

The next () method ( next () in Python 2) will return the next iterator object.

Create an iterator that returns numbers, with an initial value of 1, and gradually increasing by 1:

The StopIteration exception is used to identify the completion of the iteration to prevent an infinite loop. In the next () method, we can set the StopIteration exception to be triggered to end the iteration after the specified number of loops is completed.

Stop execution after 20 iterations:

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self
 
  def __next__(self):
    if self.a <= 20:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration
 
myclass = MyNumbers()
myiter = iter(myclass)
 
for x in myiter:
  print(x)

Guess you like

Origin blog.csdn.net/Sgmple/article/details/112795521