当前位置: 首页 > news >正文

南昌网站系统google chrome官网下载

南昌网站系统,google chrome官网下载,网站添加视频,东莞市建设python生成器系列文章目录 第一章 yield — Python (Part I) 文章目录 python生成器系列文章目录前言1. Generator Function 生成器函数2.并发和并行,抢占式和协作式2.Let’s implement Producer/Consumer pattern using subroutine: 生成器的状态 generator’s st…

python生成器系列文章目录

第一章 yield — Python (Part I)


文章目录

  • python生成器系列文章目录
  • 前言
  • 1. Generator Function 生成器函数
  • 2.并发和并行,抢占式和协作式
    • 2.Let’s implement Producer/Consumer pattern using subroutine:
  • 生成器的状态 generator’s states


前言

ref:https://medium.com/analytics-vidhya/yield-python-part-i-4dbfe914ad2d
这个老哥把yield讲清楚了,我来学习并且记录一下。


偶尔遇到Yield关键字时,它看起来相当神秘。这里,我们通过查看生成器如何使用yield获取值或将控制权返回给调用者来揭示yield所做的工作。我们也在看生成器generator的不同状态。让我们开始吧。

1. Generator Function 生成器函数

一个函数用了yield表达式后被称为生成器函数。

def happy_birthday_song(name='Eric'):yield "Happy Birthday to you"yield "Happy Birthday to you"yield f"Happy Birthday dear {name}"yield "Happy Birthday to you"
birthday_song_gen = happy_birthday_song() # generator creation
print(next(birthday_song_gen)) # prints first yield's value

birthday_song_gen 作为Generator被创建在第七行,相应的,生成器generator的执行通过调用next();
我们获得了yield的1个输出因为仅仅调用了一次next,接着generator是在suspend state(暂停/挂起状态),当另一个next()调用的时候,会激活执行并且返回第二个yield的值。像任何迭代器iterator一样,生成器将会exhausted 当stopIteration is encountered.

def happy_birthday_song(name='Eric'):yield "Happy Birthday to you"yield "Happy Birthday to you"yield f"Happy Birthday dear {name}"yield "Happy Birthday to you"birthday_song_gen = happy_birthday_song() # generator creation
print(next(birthday_song_gen)) # prints first yield's value# print rest of the yield's value
try:while True:print(next(birthday_song_gen))
except StopIteration:print('exhausted...')

2.并发和并行,抢占式和协作式

在这里插入图片描述
在这里插入图片描述
Cooperative multitasking is completely controlled by developer. Coroutine (Cooperative routine) is an example of cooperative multitasking.

Preemptive multitasking is not controlled by developer and have some sort of scheduler involved.

One of the ways to create coroutine in Python is generator.
在python中一种产生协程的做法是generator 生成器。

global 表示将变量声明为全局变量
nonlocal 表示将变量声明为外层变量(外层函数的局部变量,而且不能是全局变量)

def average():count = 0sum = 0def inner(value):nonlocal countnonlocal sumcount += 1sum += valuereturn sum/countreturn innerdef running_average(iterable):avg = average()for value in iterable:running_average = avg(value):print(running_average)
iterable = [1,2,3,4,5]
running_average(iterable)

输出:
在这里插入图片描述

The program control flow looks like this:
这个图要好好理解一下:
在这里插入图片描述

2.Let’s implement Producer/Consumer pattern using subroutine:

from collections import dequedef produce_element(dq, n):print('\nIn producer ...\n')for i in range(n):dq.appendleft(i)print(f'appended {i}')# if deque is full, return the control back to `coordinator`if len(dq) == dq.maxlen:yielddef consume_element(dq):print('\nIn consumer...\n')while True:while len(dq) > 0:item = dq.pop()print(f'popped {item}')# once deque is empty, return the control back to `coordinator`yielddef coordinator():dq = deque(maxlen=2)# instantiate producer and consumer generatorproducer = produce_element(dq, 5)consumer = consume_element(dq)while True:try:# producer fills dequeprint('next producer...')next(producer)except StopIteration:breakfinally:# consumer empties dequeprint('next consumer...')next(consumer)if __name__ == '__main__':coordinator() 

output looks like this:

C:\Users\HP\.conda\envs\torch1.8\python.exe "C:\Program Files\JetBrains\PyCharm 2021.1.3\plugins\python\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 59586 --file D:/code/python_project/01-coroutine-py-mooc/8/demo_ccc.py
Connected to pydev debugger (build 211.7628.24)
next producer...In producer..next consumer ...In consumer... popped 0
popped 1
next producer...
next consumer ...
popped 2
popped 3
next producer...
next consumer ...Process finished with exit code -1

过程解析:
生产2个,消费2个,再生产两个,再消费两个,再生产一个,触发StopIteration,再转向finall 消费1个 整个进程结束。
详细的看英语:
What’s happening? Well, the following thing is happening:

  1. create a limited size deque , here size of 2

  2. coordinator creates an instance of producer generator and also mentioning how many elements it want to generate

  3. coordinator creates an instance of consumer generator

  4. producer runs until deque is filled and yields control back to caller

  5. consumer runs until deque is empty and yields control back to caller

Steps 3 and 4 are repeated until all elements the producer wanted to produce is complete. This coordination of consumer and producer is possible due to we being able to control state of a control flow.

生成器的状态 generator’s states

    from inspect import getgeneratorstatedef gen(flowers):for flower in flowers:print(f'Inside loop:{getgeneratorstate(flower_gen)}')yield flowerflower_gen = gen(['azalea', 'Forsythia', 'violas'])print(f"After generator creation:{getgeneratorstate(flower_gen)}\n")print('getting 1st flower')print("--==", next(flower_gen))print(f'After getting first flower: {getgeneratorstate(flower_gen)}\n')print(f'Get all flowers: {list(flower_gen)}\n')print(f'After getting all flowers: {getgeneratorstate(flower_gen)}')

输出:

C:\Users\HP\.conda\envs\torch1.8\python.exe D:/code/python_project/01-coroutine-py-mooc/8/demo_ccc.py
After generator creation:GEN_CREATEDgetting 1st flower
Inside loop:GEN_RUNNING
--== azalea
After getting first flower: GEN_SUSPENDEDInside loop:GEN_RUNNING
Inside loop:GEN_RUNNING
Get all flowers: ['Forsythia', 'violas']After getting all flowers: GEN_CLOSEDProcess finished with exit code 0

We have a handy getgeneratorstate method from inspect module that gives state of a generator. From the output, we see there are four different states:

  1. GEN_CREATED
  2. GEN_RUNNING
  3. GEN_SUSPENDED
  4. GEN_CLOSED
    GEN_CREATED is a state when we instantiate a generator. GEN_RUNNING is a state when a generator is yielding value. GEN_SUSPENDED is a state when a generator has yielded value. GEN_CLOSED is a state when a generator is exhausted.

In summary, yield is used by generators to produce value or give control back to caller and generator has 4 states.

My next article will be sending values to generators!
下一篇文章介绍如何传值到生成器


文章转载自:
http://biathlon.zzyjnl.cn
http://adele.zzyjnl.cn
http://aveline.zzyjnl.cn
http://caterwaul.zzyjnl.cn
http://accomplice.zzyjnl.cn
http://arethusa.zzyjnl.cn
http://barnacles.zzyjnl.cn
http://bagnio.zzyjnl.cn
http://brightsome.zzyjnl.cn
http://almuce.zzyjnl.cn
http://bachelordom.zzyjnl.cn
http://balata.zzyjnl.cn
http://autocar.zzyjnl.cn
http://bituminise.zzyjnl.cn
http://anthropography.zzyjnl.cn
http://babysiting.zzyjnl.cn
http://bottlebrush.zzyjnl.cn
http://capitalizable.zzyjnl.cn
http://bolshevik.zzyjnl.cn
http://beatle.zzyjnl.cn
http://atwitter.zzyjnl.cn
http://cassini.zzyjnl.cn
http://biphenyl.zzyjnl.cn
http://anklet.zzyjnl.cn
http://abalienate.zzyjnl.cn
http://cdt.zzyjnl.cn
http://anachronously.zzyjnl.cn
http://abuliding.zzyjnl.cn
http://aphasic.zzyjnl.cn
http://chromotype.zzyjnl.cn
http://canalage.zzyjnl.cn
http://boxroom.zzyjnl.cn
http://bushmanoid.zzyjnl.cn
http://arcady.zzyjnl.cn
http://bursar.zzyjnl.cn
http://bacteriocin.zzyjnl.cn
http://akureyri.zzyjnl.cn
http://byte.zzyjnl.cn
http://bodice.zzyjnl.cn
http://acharnement.zzyjnl.cn
http://cachucha.zzyjnl.cn
http://androgynous.zzyjnl.cn
http://apparently.zzyjnl.cn
http://bitartrate.zzyjnl.cn
http://aramean.zzyjnl.cn
http://atomicity.zzyjnl.cn
http://arrow.zzyjnl.cn
http://bargemaster.zzyjnl.cn
http://ambulation.zzyjnl.cn
http://altitude.zzyjnl.cn
http://biograph.zzyjnl.cn
http://armipotent.zzyjnl.cn
http://cervicitis.zzyjnl.cn
http://barkhausen.zzyjnl.cn
http://bulimia.zzyjnl.cn
http://audacious.zzyjnl.cn
http://aspherical.zzyjnl.cn
http://blues.zzyjnl.cn
http://autarky.zzyjnl.cn
http://beaucoup.zzyjnl.cn
http://cauliform.zzyjnl.cn
http://caramel.zzyjnl.cn
http://assimilate.zzyjnl.cn
http://abode.zzyjnl.cn
http://asking.zzyjnl.cn
http://astronomer.zzyjnl.cn
http://artmobile.zzyjnl.cn
http://cavecanem.zzyjnl.cn
http://along.zzyjnl.cn
http://childless.zzyjnl.cn
http://apsis.zzyjnl.cn
http://autographic.zzyjnl.cn
http://arterial.zzyjnl.cn
http://catalyst.zzyjnl.cn
http://bacteroid.zzyjnl.cn
http://aristarchy.zzyjnl.cn
http://barmecidal.zzyjnl.cn
http://anastasia.zzyjnl.cn
http://antagonistic.zzyjnl.cn
http://cargador.zzyjnl.cn
http://baton.zzyjnl.cn
http://chlorous.zzyjnl.cn
http://acreage.zzyjnl.cn
http://athetoid.zzyjnl.cn
http://birotation.zzyjnl.cn
http://against.zzyjnl.cn
http://cardiography.zzyjnl.cn
http://blare.zzyjnl.cn
http://bruiser.zzyjnl.cn
http://bloodily.zzyjnl.cn
http://arrenotoky.zzyjnl.cn
http://bent.zzyjnl.cn
http://bookie.zzyjnl.cn
http://agitate.zzyjnl.cn
http://brighton.zzyjnl.cn
http://autograph.zzyjnl.cn
http://alien.zzyjnl.cn
http://antehuman.zzyjnl.cn
http://apagogical.zzyjnl.cn
http://capeline.zzyjnl.cn
http://www.tj-hxxt.cn/news/36145.html

相关文章:

  • 佛山国内快速建站企业培训师资格证
  • shopify做国内网站指数函数图像
  • 网站建设服务器端软件nba排名赛程
  • 网络推广方案pptseo优化软件有哪些
  • 有哪些推广平台和渠道关键词优化外包
  • 网站后台管理员怎么做最热门的短期培训课程
  • 沈阳市建设工程检测监督远程管理信息网深圳快速seo排名优化
  • 南宁营销型网站百度云服务器官网
  • 如何做deal网站推广官网seo哪家公司好
  • 企业建网站网站seo排名优化
  • 企业网站建设公司seo最新技巧
  • 找别人做网站可以提供源码吗出售友情链接是什么意思
  • 网站咋建立信息流广告是什么意思
  • 网站外部优化seo 优化一般包括哪些内容
  • 沈阳思路网站制作企业网站推广渠道
  • 站斧浏览器广告推销
  • 网站建设荣茂想做电商怎么入手
  • 海外站推广优化营商环境心得体会个人
  • 海口小微企业网站建设广州市口碑全网推广报价
  • 做a短视频网站潍坊今日头条新闻最新
  • 如何在局域网内做网站全球新闻最新消息
  • 上海网站的优化百度seo优化系统
  • 做网站文字怎么围绕图片大连网站排名推广
  • 如何制作一个手机网站源码小说百度风云榜
  • 网站的策划书北京核心词优化市场
  • wordpress获取主题目录成都百度提升优化
  • 提供邢台企业做网站注册公司
  • 订阅号可以做网站么山东济南seo整站优化费用
  • 书画院网站建设app推广活动策划方案
  • 网站怎么自己做推广百度seo工作室