iterator/generator

iterators and generators

1. Iterator

  An iterator is a way to access the elements of a collection. Iterator objects are accessed from the first element of the collection until all elements have been accessed. Iterators can only go forward and not backward, but that's fine, because people rarely go backwards on the way of iterators. In addition, one of the great advantages of iterators is that they do not require all elements to be prepared in advance for the entire iteration. The iterator only evaluates an element when it iterates to the element, and before or after that, the element may not exist or be destroyed. This feature makes it especially suitable for traversing some huge or infinite collections, such as several G files.

  Features:

    1. The visitor does not need the internal structure of the relationship iterator, but only needs to continue to get the next content through the next() method

    2. A value in the collection cannot be accessed randomly, but can only be accessed sequentially from the beginning to the end

    3. You cannot go back when the visit is halfway through

    4. It is convenient to cycle relatively large data sets and save memory

2. Generator

  A function that returns an iterator when called is called a generator; if the function contains yield syntax, the function becomes a generator;

In the above code: func is a function called a generator, and when this function func() is executed, an iterator will be obtained.

3. Examples

  a. Use the generator to customize the range

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325219834&siteId=291194637