Xiao Li is 30 years old and wants to find a boyfriend. Now she has two ways
- there will be a blind date next month, with 100 consecutive blind dates (one-time return group of objects)
- find a matchmaker. The matchmaker will continuously introduce Xiao Li to her date. If Xiao Li goes on a blind date one by one, she can start tomorrow (yield returns results one by one)
for the loop, both methods are blind dates (traversing) one by one, but the first method can not start until all the blind dates (elements) are in place, and it takes more time to publicize the gathering of participants (generating elements). Larger venue (memory space), the second generator method, Xiao Li and the matchmaker said I want a blind date (element), and the matchmaker found one to give to Xiao Li. Xiao Li completes the blind date, calls the second object (the next () method of the iterative object), and continues the blind date.
this operation reduces the waiting time and does not need such a big house. The savings are considerable.
the general function is to generate all the data returned at once.
if you want to take each data as needed, then use for to iterate, but what if there is too much data?
needs a rule to generate data, which returns one item of data each time according to the rule. This is the
of yield.
>>> def gen(n):
i = 0
while i < n:
i += 1
yield i
>>> for s in gen(10):
print(s)
gen (10) does not calculate 10 values at once, but generates them one by one during iteration.
One of the main meanings of the
generator is to avoid taking up more memory.
when multiple values are required, you can return one at a time and slowly calculate
class fib():
def __init__(self):
self.a = 0
self.b = 1
def __iter__(self):
while(1):
yield self.b
self.a, self.b = self.b, self.a+self.b
b = iter (fib ())
b.next ()
calculate the Fibonacci series, as many as you want.
it seems that the following can be better reflected:
def process_dir (dir):
if is file
yield process_file(file)
if is dir
process_dir()
suddenly a flash: generator returns an iterative class (I don't know if it's called this) and can be iterated. Although generator is no different from the general function in for, while and other statements, but in some places, the general function is not competent. For example, in higher-order functions such as map, parameters are required to be iterated, so you can only use generator.
I don't know if what I said is right. Welcome to spray
you can reduce the number of products produced every time you use it. It's there
.