python list generator vs generator

List generators are very simple yet very powerful built into python.

To generate a list [1,2,3,4] you can use list(range(1,5))

blob.png

List Builder Application

blob.png

If the above formula is added with judgment, the desired results can be filtered out, for example, only the square of even numbers is required

blob.png

Use multiple loops

blob.png



Builder

The essential difference between a generator and a list generator is that one has already generated data. When using it, if the data is too large, it will cause memory overflow, while the generator will only generate data when it is looped.

The difference between a generator and a list generator is that one is [] and the other is ()

generator writing

g=(x x ())
(g)

blob.png

The way to print generator is next(g) and for loop

blob.png


Use the form of a function to print the Fibonacci sequence

(max):
    nab=n < max:
        (b)
        ab = ba + b
        n=n+fib()

blob.png

The above function is only one step away from the generator. To turn the fib function into a generator, just change print(b) to yield.

(max):
    nab=n < max:
        b
        ab = ba + b
        n=n+fib()


Generator method to print fib

i fib():
    (i)

If you want to get the return value when you use the for loop to call the generator, you need to catch the stopIteration error, and the return value is included in the value of stopIteration:

g=fib(6)

(max):
    nab=n < max:
        b
        ab = ba + b
        n=n+g=fib()
:
    :
        x=(g)
        (x)
    e:
        (e.value)

blob.png


Guess you like

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