Python Generator and Application

Source: Internet
Author: User
Keywords python generator python generator application
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)
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.