Generator knowledge point finishing

list comprehension

  • a = [i + 1 for i in range(10)]

generator

  • The mechanism of calculating while looping
  • A data type that automatically implements the iterator protocol and is an iterable object.
  • Implement delayed computing, execute on demand, and save memory

generator classification

  • Generator function, using yield to return results and pending status
  • Generator expression, the generator returns an object that produces results on demand, called with a for loop or the next() method.

yield

  • A function definition contains yield , then calling this function is a generator
  • return is in the generator, representing the termination of the generator, reporting a StopIteration error
  • The role of yield

    • yield can return the internal data of the generator
    • Suspend the current function execution process
    • Inherit current state
    • Call the generator again to continue execution from where it left off

generator send method

  • yield can receive external signals from functions
  • The role of generator.send(sign)

    • Wake up the generator and continue execution
    • send a message inside the generator

generator call method

  • next() call
  • for loop call

    • Can get the return of yield
    • Can't get the return value of the return statement
    • To get the return, the StopIteration error must be caught, and the return value is contained in StopIteration.value

Iterable object (Iterable)

  • Objects that can act directly on a for loop are collectively called iterable objects
  • data set (list, tuple, dict, set, fronzset, str)
  • generator generator

Iterator

  • An object that can be called by the next() function and continuously returns the next value is called an iterator
  • The iterator represents a data stream, which can be regarded as an ordered sequence, but the length cannot be known in advance

    • Use of next()

      • next(Iterator)
      • Iterator.__next__()

Data collections and generators

  • are iterable objects (Iterable)
  • A generator is an ordered stream of data that can represent an infinite stream of data
  • The data set is of finite length
  • can be called in a for loop
  • Only generators can be called by _next()_

You can use isinstance() to determine whether an object is an Iterable object:

>>> from collections import Iterable
>>> isinstance([], Iterable)
True
>>> isinstance({}, Iterable)
True
>>> isinstance('abc', Iterable)
True
>>> isinstance((x for x in range(10)), Iterable)
True
>>> isinstance(100, Iterable)
False

You can use isinstance() to determine whether an object is an Iterator object:

>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
True
>>> isinstance([], Iterator)
False
>>> isinstance({}, Iterator)
False
>>> isinstance('abc', Iterator)
False

Guess you like

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