Eleven, python generators and iterators

1. List Compilation:
1. Generate a list:
list = [ i*2 for i in range(10)] #Use list comprehension to generate a list, occupying memory space, and it will cause a lot of waste when the number is large.
print(list)
 
2. Use a generator to generate a list: (generator)
list1 = ( i*2 for i in range(10)) #Store the formula for generating the list in a variable, take it when needed, (Note: the disadvantage is that it can only be taken one by one)
print(list1.__next__()) #Use __next__ to fetch data, one number at a time, throw StopIteration error when finished
for i in list1: #Because it is troublesome to take one at a time, we can also use a for loop to take
    print(i)                
 
3. If the result that needs to be calculated cannot be generated using a list, we can also use a function to make a generator, such as a Fibonacci sequence.
Fibonacci sequence: (fibonacci)
Introduction: The Fibonacci sequence is a kind of number except the first and second numbers, any number can be obtained by adding the first two numbers
The Fibonacci sequence is implemented by a python function:
def fib(a,b,max): #a refers to the first number in Fibonacci, b refers to the second number in Fibonacci, and max refers to adding several times
    n=0
    while n<max:
        print(b)
        a,b=b,a+b
        n=n+1
        return'done'
fib(10,15,12)
If you want to turn the above function into a generator, just change print(b) to yield b
yield: Return the result each time yield is called, save the current position, and continue from the saved position when executing again.
def fib(a,b,max):
    n = 0
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'
 
f = (fib(10,15,12)) #Specify the function as a variable, and use the variable to take the value, otherwise it is impossible to pass the parameter while taking the value.
print(f.__next__())
print(f.__next__())
print(f.__next__())
 

Guess you like

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