Python generator and application instance parsing, python Generator
This article focuses on the Python generator and its application, as follows.
I. 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 iteratable object.
2. Two generator forms (Python provides generators in two different ways)
1. Generator function: General function definition. However, use the yield statement instead of the return Statement to return the result. The yield statement returns a result at a time. In the middle of each result, the function state is suspended so that it can continue to be executed next time when it leaves.
Yield features:
- Execute the function result as an iterator (encapsulate _ iter __,__ next _ in an elegant way __)
- The status of function pause and re-running is caused 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 Iteratorprint (isinstance (g, Iterator) # determine whether it is an Iterator object print (next (g )) print ('=>') print (next (g )) print ('=>') print (next (g) for I in g: # I = iter (g) print (I)
Note: What is the comparison between yield and return?
- Same: both have the function of returning values.
- Different: return can only return one value, while yield can return multiple values
2. Generator expression: similar to list derivation. However, the generator returns an object that generates results on demand, instead of building a result list 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))
Iii. Application
# [{'Name': 'apple', 'price': 333, 'Count': 3},] file Content # complete file reading and operations through the generator interpreter 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)
Summary
The above is all about the Python generator and application instance parsing in this article. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!