python generator

With list comprehensions, we can directly create a list. However, due to memory constraints, the list capacity is definitely limited. Moreover, creating a list with 1 million elements not only takes up a lot of storage space, but if we only need to access the first few elements, then most of the space occupied by the latter elements is wasted.

So, if the elements of the list can be calculated according to a certain algorithm, can we continue to calculate the subsequent elements in the process of looping? This saves a lot of space by not having to create a complete list. In Python, this mechanism of computing while looping is called a generator: generator.

To create a generator, there are many ways. The first method is very simple, as long as a list comprehension is []changed ()to create a generator:

>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>

  The biggest difference between creating a list comprehension and a generator is: comprehension[] , generator()

retrieve data

>>> for i in g:
...     print(i)

  

 

 

If yield is defined in a function, then this function is no longer an ordinary function, but a generator

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'

use:

1 >>> for i in fib(6):
2 ...     print(i)
3 ...
4 1
5 1
6 2
7 3
8 5
9 8
View Code

 

Guess you like

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