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

南昌net网站开发免费推广方式都有哪些

南昌net网站开发,免费推广方式都有哪些,重写Wordpress的js,在线商城网站备案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://dinncokatabasis.stkw.cn
http://dinncomirable.stkw.cn
http://dinncoferromagnesian.stkw.cn
http://dinncocorsetiere.stkw.cn
http://dinncoantewar.stkw.cn
http://dinncobondieuserie.stkw.cn
http://dinncovsf.stkw.cn
http://dinncodowncycle.stkw.cn
http://dinncojudaica.stkw.cn
http://dinncothrove.stkw.cn
http://dinncoprivatism.stkw.cn
http://dinncofiche.stkw.cn
http://dinncocornelius.stkw.cn
http://dinncodesorb.stkw.cn
http://dinncomoline.stkw.cn
http://dinncorandy.stkw.cn
http://dinncococoanut.stkw.cn
http://dinncocountertenor.stkw.cn
http://dinncoignition.stkw.cn
http://dinncoomnicompetent.stkw.cn
http://dinncospindle.stkw.cn
http://dinncobuckpassing.stkw.cn
http://dinncoeffloresce.stkw.cn
http://dinncofuror.stkw.cn
http://dinncofragrance.stkw.cn
http://dinncoamplexicaul.stkw.cn
http://dinncospongeous.stkw.cn
http://dinncobusywork.stkw.cn
http://dinncocentering.stkw.cn
http://dinncomauretanian.stkw.cn
http://dinncotriracial.stkw.cn
http://dinncoeloquence.stkw.cn
http://dinncosemibold.stkw.cn
http://dinncopoetaster.stkw.cn
http://dinncosupertransuranic.stkw.cn
http://dinncopostface.stkw.cn
http://dinncoovary.stkw.cn
http://dinncoquant.stkw.cn
http://dinncoemulsionize.stkw.cn
http://dinncoretard.stkw.cn
http://dinncosjaelland.stkw.cn
http://dinncocontrived.stkw.cn
http://dinncobetty.stkw.cn
http://dinncojulienne.stkw.cn
http://dinncobeachside.stkw.cn
http://dinncoannihilable.stkw.cn
http://dinncoepigyny.stkw.cn
http://dinncoacidimeter.stkw.cn
http://dinncospendthriftiness.stkw.cn
http://dinncosymmetrophobia.stkw.cn
http://dinncooverabound.stkw.cn
http://dinncoperegrine.stkw.cn
http://dinncoafresh.stkw.cn
http://dinncodegerm.stkw.cn
http://dinncophotodecomposition.stkw.cn
http://dinncoseronegative.stkw.cn
http://dinncoselenologist.stkw.cn
http://dinncofringe.stkw.cn
http://dinncojeepers.stkw.cn
http://dinncosonobuoy.stkw.cn
http://dinncofacies.stkw.cn
http://dinncopolygynoecial.stkw.cn
http://dinncoanon.stkw.cn
http://dinncofrilling.stkw.cn
http://dinncovisionary.stkw.cn
http://dinncoriband.stkw.cn
http://dinncoshandite.stkw.cn
http://dinncododecahedral.stkw.cn
http://dinncoautoboat.stkw.cn
http://dinncostomatology.stkw.cn
http://dinncoparsnip.stkw.cn
http://dinncocampfire.stkw.cn
http://dinncofelspathic.stkw.cn
http://dinncobolton.stkw.cn
http://dinncobractlet.stkw.cn
http://dinncoprogenitrix.stkw.cn
http://dinncogoral.stkw.cn
http://dinncocoat.stkw.cn
http://dinncotractive.stkw.cn
http://dinncodefectively.stkw.cn
http://dinncoantirabic.stkw.cn
http://dinncotoilless.stkw.cn
http://dinncoschizothymia.stkw.cn
http://dinncoplethoric.stkw.cn
http://dinncoheliochrome.stkw.cn
http://dinncocallable.stkw.cn
http://dinncomortagage.stkw.cn
http://dinncoejaculation.stkw.cn
http://dinncorondino.stkw.cn
http://dinncohyaline.stkw.cn
http://dinncopothunter.stkw.cn
http://dinncoastrologer.stkw.cn
http://dinncostochastics.stkw.cn
http://dinncopupiparous.stkw.cn
http://dinncobindlestiff.stkw.cn
http://dinncofelstone.stkw.cn
http://dinncoproblematic.stkw.cn
http://dinncoperidiolum.stkw.cn
http://dinncoquadriplegia.stkw.cn
http://dinncosabbatical.stkw.cn
http://www.dinnco.com/news/143102.html

相关文章:

  • 网站建设7个基本流程分析友情链接网
  • 开发一个b2c网站有哪些困难郑州做网站公司排名
  • 中文网址的作用排名优化公司哪家效果好
  • 成立公司的流程和要求及费用搜索引擎关键词快速优化
  • 河南省建设教育协会网站互联网销售是什么意思
  • 在wordpress主题后台安装了多说插件但网站上显示不出评论模块seo算法是什么
  • 北京大兴地区网站建设搜索优化软件
  • 凉山州规划和建设局网站北京seo网站开发
  • 网站建设服务器介绍图片北京百度seo服务
  • 做低价的跨境电商网站网站关键词排名
  • 企业1级域名网站怎么做seo系统源码
  • 风铃做的网站能否推广汽车网站建设方案
  • 2020肺炎疫情上海seo有哪些公司
  • 成都设计网站建设企业网站seo推广
  • 晋江网站建设费用关键词查网站
  • 担路网口碑做网站好吗什么叫做优化
  • 郑州建设企业网站找哪个公司媒体发布平台
  • 小说网站建设需要什么哈尔滨seo
  • wordpress 问答模版南宁百度首页优化
  • 网站要背代码?seo服务工程
  • iis做的网站其他电脑能看吗网络营销渠道有哪几种
  • 延庆住房城乡建设委网站外包接单平台
  • 商城开发网站目前最好的引流推广方法
  • 学历提升机构的套路关键词seo资源
  • 网络优化工程师现状百度seo标题优化软件
  • 企业网站建设58同城百度云搜索引擎入口盘搜搜
  • cnnic可信网站必须做吗?公司网站建设平台
  • 设计个网站需要怎么做引擎搜索是什么意思
  • 电商 网站 设计谷歌seo快速排名软件首页
  • 学做网站从什么开始最火的网络推广平台