Tour Python eight: iterators and generators

1, iterators

Iterator is a way to access the collection elements. 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, but that's OK, because people rarely go back in an iterative way. In addition, a major advantage of the iterator is not required to be prepared in advance throughout the iterative process all the elements. Iterator iterative calculation only when the element to an element, and before or after the element can not exist or be destroyed. This feature makes it particularly suitable for traversing some huge or infinite set, such as several files G

Features:

  1. Visitors do not need to be concerned about the internal structure of the iterator, only () methods continue to be removed by a content next.
  2. Can not access a random set of values ​​can only be accessed sequentially from beginning to end.
  3. When access can not retreat back to half.
  4. Cycle facilitates relatively large data sets, to save memory.
1 >>> a = iter([1,2,3,4,5])
2 >>> a
3 <list_iterator object at 0x101402630>
4 >>> a.__next__()
5 1
6 >>> a.__next__()
7 2
8 >>> a.__next__()
9 3
10 >>> a.__next__()
11 4
12 >>> a.__next__()
13 5
14 >>> a.__next__()
15 Traceback (most recent call last):
16  File "<stdin>", line 1, in <module>
17 StopIteration

2, generator

When a function call to return an iterator, then this function is called Generator (generator); if the yield is included in the function syntax, then this will become a function generator;

1    def func():
2    yield 1
3    yield 2
4    yield 3
5    yield 4

The above code: func is a function known as a generator, when the execution of the function FUNC () will get an iterator.

1 >>> temp = func()
2 >>> temp.__next__()
3 1
4 >>> temp.__next__()
5 2
6 >>> temp.__next__()
7 3
8 >>> temp.__next__()
9 4
10 >>> temp.__next__()
11 Traceback (most recent call last):
12  File "<stdin>", line 1, in <module>
13 StopIteration

3, examples

a, using the generated range Custom

1 def nrange(num):
2     temp = -1
3     while True:
4         temp = temp + 1
5         if temp >= num:
6             return
7         else:
8             yield temp

b, using an iterative access range

...

 

Guess you like

Origin blog.csdn.net/xymalos/article/details/91511323