What is a generator? How to use Python generators?

  Generators are one of the most attractive features of the Python language. Generators are actually a special iterator, but this iterator is more elegant. It no longer needs to define the __iter__() and __next__() methods in the class as above. It only needs to declare a yield keyword in the function. So a generator is a special kind of iterator (the reverse is not true), so any generator also generates values ​​in a lazy loading mode. An example of using a generator to implement the Fibonacci sequence is:

  def fib(max):

  n, a, b = 0, 0, 1

  while n < max:

  yield b

  a, b = b, a + b

  n = n + 1

  for i in fib(10):

  print(i)

  (1)Generator object

  Simply put, a generator is a function that uses the yield keyword:

  def countdown(n):

  print('countdown start')

  while n > 0:

  yield n

  n -= 1

  print('Done!')

  print(countdown) #

  gen = countdown(5)

  print(gen) #

  # The generator object is also an iterator object. It must have iter and next, which are encapsulated by the yield keyword when the function is called. There is no need to define it yourself.

  # print(gen.__iter__())

  # print(gen.__next__())

  # print(gen.__next__())

  # print(gen.__next__())

  for i in gen:

  print(i)

  Analysis: Only one generator object will be returned when the generator function is called. Only when the generator object calls the __next__ method will the function body code execution be triggered. It will stop until the keyword yield is encountered, and the value after yield will be returned as the return value. Therefore, yield is similar to the function of return, but different from return. Yes, return returns and the function ends; while yield suspends the status of the function and waits for the generator object to call the __next__ method again. The function continues to run from the first statement after the suspended position until it meets yield again and returns. The subsequent value; if the __next__ method is continuously called and the function body is entered for the last time, and the code to be executed no longer has a yield, an iteration exception error will be reported.

  In addition, compared to iterators, generator objects have several more methods:

  (1) A built-in close method is used to close itself

  (2) A built-in send method, which enters the generator, is similar to next, but has an additional function of passing values ​​to the yield variable.

  Summary of yield’s functions:

  (1) Encapsulate the iter and next methods (2) When executing a function, yield is returned and the subsequent value is returned. Unlike return, yield can return multiple values ​​​​(3) The status of the suspended function is found when the next method is called next time. Execution continues at the corresponding pause position.

  generator expression

  There are two ways to create a generator object. One is by creating the yield keyword in the function. The other is generator expression, which is a syntax format similar to the list generation learned in data types, except that [] is replaced by (), that is:

  (expression for item in iterable if condition)

  Unlike list generation expressions, which ultimately return a list result, generator expressions, as the name implies, return a generator object, such as:

  >>> [x*x for x in range(4)] # List comprehension

  [0, 1, 4, 9]

  >>> gen=(x*x for x in range(4))

  >>> gen

  at 0x101be0ba0>

  When the values ​​are needed, the values ​​are calculated one by one by calling the next method or for loop:

  >>> next(gen)

  0

  >>> next(gen)

  1

  >>> next(gen)

  4

  >>> next(gen)

  9

  >>> next(gen)

  Traceback (most recent call last):

  File "", line 1, in

  StopIteration

  #----------------for loop------------------

  >>> gen=(x*x for x in range(4))

  >>> for i in gen:

  ... print(i)

  ...

  0

  1

  4

  9

  Iterable objects, iterators, generator relationships

  Interview questions

  def add(s, x):

  return s + x

  def gen():

  for i in range(4):

  yield i

  base = gen()

  for n in [1, 10]:

  base = (add(i, n) for i in base)

  print(list(base))

Guess you like

Origin blog.csdn.net/oldboyedu1/article/details/133344929