06 generators and iterators

Iterator

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. Access to the back half can not retreat
  4. Cycle facilitates relatively large set of data, to save memory

Builder

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;

def func():
    yield 1
    yield 2
    yield 3

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

temp = func()
print(temp.__next__())
print(temp.__next__())
print(temp.__next__())

When encountered == generator, may be used instead of the method next for loop iterates ==

Guess you like

Origin www.cnblogs.com/chenych/p/10939676.html