python-day17--Generator

Source: Internet
Author: User

1. Essence: Iterator

2. Generator function:

def func ():
A=1
b=2
Yield a #返回第一个值
Yield b #返回第二个值
ret = func ()  #拿到一个生成器
Print (Next (ret)) #取第一个值
Print (Next (ret)) #取第二个值
Print (ret) #取第三个值 An error because there is no third value

3. example of the generator listener file input
Import time
def tail (filename):
with open (filename) as F:
F.seek (0, 2) #从文件末尾算起
While True:
line = F.readline () # reads new lines of text in the file
If not line:
Time.sleep (0.1)
Continue
Yield line

Print (Next (tail (' tmp_file ')))

4. #计算移动平均值
Def averager ():
Total = 0
Day = 0
Avrage = 0
While True:
Day_num = yield avrage #return avrage
Total + = Day_num
Day + = 1
Avrage = Total/day

Avg = Averager ()
num = Next (avg) #激活生成器 avg.send (), nothing like send and next effect
Print (avg.send) #传值 Next
Print (Avg.send (20))
5. Transfer value:
#计算移动平均值
def wrap (func):
    def inner (*args,**kwargs):
g = func (*args,**kwargs)
Next (g)
Return g
return inner

@wrap
Def averager ():
Total = 0
Day = 0
Avrage = 0
While True:
Day_num = yield avrage #return avrage
Total + = Day_num
Day + = 1
Avrage = Total/day

g = Averager ()
Print (G.send (10))
Print (G.send (20))
6.
def func ():
# for I in ' AB ':
# Yield I
Yield from ' AB '
Yield from [+ +]
g = func ()
L = []
L.append (Next (g))
L.append (Next (g))
L.append (Next (g))
L.append (Next (g))
L.append (Next (g))
Print (L)






python-day17--Generator

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.