1-13 Python iterators and generators

 

Iterator

Iteration is one of the most powerful features of Python 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.

Iterator has two basic methods: ITER ()  and  Next () .

Strings, lists, tuples or objects can be used to create an iterator:

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

Iterator object can be used for conventional traverse statement:

#!/usr/bin/python3
 
list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
for x in it:
    print (x, end=" ")

Performing the above procedure, the output results are as follows:

1 2 3 4

You can also use next () function:

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

Performing the above procedure, the output results are as follows:

1
2
3
4

Creating an iterator

The class as a need to implement an iterator use two methods in a class the __iter __ () __ with the __next () .

If you already understand object-oriented programming, we know there is a class constructor, Python's constructor __init __ (), which will be executed when the object is initialized.

Read more: A Python 3 Object Oriented

the __iter __ () method returns a special iterator object, the iterator object implements the __next __ () method and by StopIteration abnormality flag iterations is completed.

the __next __ () method (Python 2 is in the Next ()) returns the next iteration object.

Creating a Returns an iterator, the initial value of 1, gradually increasing 1:

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self
 
  def __next__(self):
    x = self.a
    self.a += 1
    return x
 
myclass = MyNumbers()
myiter = iter(myclass)
 
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

Execution output is:

1
2
3
4
5

StopIteration

StopIteration exception for complete identification iteration, prevent an infinite loop , in __next __ () method, we can set the trigger StopIteration after finishing the specified number of cycles to end the abnormal iteration.

After 20 iterations stop execution:

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)

Execution output is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Builder

In Python, using a function generator is referred to as yield (Generator) .

The difference is that with an ordinary function, the generator is a return iterator function can only be used for iterative operations, more simply understood generator is a iterator.

During the call generator is running, each encounter yield function pauses and save all of the current operating information, the return value of yield, and the next execution of the next () continue to operate from its current position method.

Calling a generator function, it returns an iterator object.

The following example uses yield achieved Fibonacci columns:

#!/usr/bin/python3
 
import sys
 
def fibonacci(n): # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): 
            return
        yield a
        a, b = b, a + b
        counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
 
while True:
    try:
        print (next(f), end=" ")
    except StopIteration:
        sys.exit()

Performing the above procedure, the output results are as follows:

0 1 1 2 3 5 8 13 21 34 55

 

Guess you like

Origin blog.csdn.net/u012717715/article/details/91957606