First. Definition
It can be understood as a data type, which automatically implements the iterator protocol (other data types need to call their own built-in __iter__ method), so the
generator is an iterable object
Second, the two forms of
generators (Python has two different ways to provide generators)
1. Generator function: regular function definition, however, use the yield statement instead of the return statement to return the result. The yield statement returns one result at a time, and in the middle of each result, suspend the state of the function so that it can continue to execute where it left next time.
Yield's function:
1 Make the result of the function as an iterator (encapsulate __iter__,__next__ in an elegant way)
2 The state of function pause and resume operation is determined by yield
def func():
print('first')
yield 11111111
print('second')
yield 2222222
print('third')
yield 33333333
print('fourth')
g=func()
print(g)
from collections import Iterator
print(isinstance(g,Iterator)) #Determine whether it is an iterator object
print(next(g))
print('======>')
print(next(g))
print('======>')
print(next(g))
print('======>')
print(next(g))
for i in g: #i=iter(g)
print(i)
Note: Comparison between yield and return?
Same: all have the function of return value
Different: return can only return a value, and yield can return multiple values
2.
Generator expression: similar to list comprehension, however, the generator returns an object that produces results on demand, rather than constructing a list of results at a time
g=('egg%s' %i for i in range(1000))
print(g)
print(next(g))
print(next(g))
print(next(g))
with open('a.txt',encoding='utf-8') as f:
# res=max((len(line) for line in f))
res=max(len(line) for line in f)
print(res)
print(max([1,2,3,4,5,6]))
with open('a.txt',encoding='utf-8') as f:
g=(len(line) for line in f)
print(max(g))
print(max(g))
print(max(g))
Third. Application
# [{'name':'apple','price': 333,'count': 3}, ]File content
#Complete the reading and following operations of the file through the generator expression
with open('db.txt',encoding='utf-8') as f:
info=[{'name':line.split()[0],
'price':float(line.split()[1]),
'count':int(line.split()[2])} for line in f if float(line.split()[1]) >= 30000]
print(info)