Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky
The generator
It is now possible to create a list directly using the generator, but due to memory limitations, the list is bound to have a limited capacity. If we need a list of hundreds of elements, but only a few of them are accessed at a time, then it would be a waste of memory to not use the rest of the elements.
This is where the Generator comes into play. It generates new data according to some algorithm until a specified condition is satisfied
There are several ways to get the generated formula:
-
To get a generator using a list generator, sample code is as follows:
G = (x for x in range(10)) # change [] to () # print(type(g)) # <class 'generator'> # print(g.__next__()) # 0 print (g. __next__ ()) # 1 print (g. __next__ ()) # 2 print (g. __next__ ()) # 3 print (g. __next__ ()) # 4 # use. Call __next__ way Print (next(g)) # 5 print(next(g)) # 6 print(next(g)) # 7 print(next(g)) # 8 print(next(g)) # 9 Print (next(g)) # Raise error StopIteration when no data is calledCopy the code
Call as much as you need. If you don’t call it, it won’t be generated, and it won’t take up memory space. You can use a loop structure to call it as needed
G = (x for x in range(10)) # change [] to () skip = True # count = 0 Print (next(g)) if count > 9: break #Copy the code
-
Use the yield keyword to complete a generator that generates the first 20 numbers of the Fibonacci sequence:
def fun(length): a, b = 0, 1 for _ in range(length): A, b = b, a + b yield a fib = fun(20) print(type(fib)) # <class 'generator'> # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 print(next(fib), "", end="") count += 1Copy the code
The process is as follows:
During execution, execution is paused when the yield keyword is encountered, and the next call continues where it was paused because it is a loop, so it jumps directly to the for statement
If you’re calling yield and you need to give it a value, you use.send(). Example code is as follows:
def fun(num): n = 0 for i in range(num + 1): G = fun(3) print(g.end (None)) print(g.end ('3')) print(g.end ('3')) print(g.end ('3')) Print (g.end ('3')) "" print(g.end ('3'))" "Copy the code
The addition of send makes the generator more flexible, but it is important to note that the first time the generator’s send() method is called, the argument must be None, otherwise an exception will be thrown. It is also possible to call the next() method once before calling the send() method, so that the generator enters the yield expression first.
Iterators and iterable generators
Iterable objects include generators, tuples, lists, collections, dictionaries, and strings
The collections Iterable function is combined with isinstance(object, classinfo) to determine that an object is not an Iterable
Iteration is a way of accessing elements of a collection. An iterator is an object that remembers the position of the iterator. Iterator objects are accessed from the first element of the collection until all elements have been accessed. Iterators can only move forward and not backward. Most generators are also iterators.
Objects that can be called by the next () function and keep returning the next value are called iterators: iterators. We can use isinstance() to determine if an object is an Iterator:
Note: an iterable is not necessarily a generator, but a generator must be iterable.
Iterators can be turned from tuples, lists, sets, dictionaries, and strings to iterators using the iter() function
Iterable differs from Iterator**** in that Iterable is a general term for objects that can be used as a for loop; The Iterator must be called by next() before it returns the next iteration. The iteration error is raised when there is no more data. The length of the Iterator is not known until next() calls it. Iterator can even represent an infinitely large stream of data, such as all natural numbers.
from collections.abc import Iterable, Iterator a = [1, 2, 3] b = {1, 2, 3} c = (1, 2, F = (x for x in range(5)) print(type(a)) # <class 'list'> print(type(b)) # <class 'set'> print(type(c)) # <class 'tuple'> print(type(d)) # <class 'str'> print(type(e)) # <class 'int'> print(type(f)) # <class 'generator'> print("-" * 20) print(isinstance(a, Iterable)) # True print(isinstance(b, Iterable)) # True print(isinstance(c, Iterable)) # True print(isinstance(d, Iterable)) # True print(isinstance(e, Iterable)) # False print(isinstance(f, Iterable)) # True print("-" * 20) Iterator)) # False print(isinstance(b, Iterator)) # False print(isinstance(c, Iterator)) # False print(isinstance(d, Iterator)) # False print(isinstance(f, Print ("-" * 20) print(isinstance(iter(a), Iterator)) # True print(isinstance(iter(b), Iterator)) # True print(isinstance(iter(c), Iterator)) # True print(isinstance(iter(d), Iterator)) # TrueCopy the code