python--a small test of the generator

Source: Internet
Author: User

"" "1, the generator is Object 2, each time the next () method is called to return a value until the Stopiteration exception 3 is thrown, how to create a generator? Simply write a normal function and include the yield statement instead of the return statement, so Python automatically marks the function as Generator 4, and the yield statement's primary function is to return a value just like the return statement, but most importantly, the most important thing to understand is that After the yield statement returns a value, the interpreter saves a reference to the stack      it will be used for the next call to next () when the reply function executes "" "#创建一个生成器def  mygen ():     yield 1    yield 2    yield  "a"      yield  "B" # print (MyGen ())   #此刻, prints out a generator object # g = mygen () #  print (Next (g)) # print (Next (g)) # print (Next (g)) # print (Next (g)) #print (Next (g))  # The last data has been reached, and if you continue printing then throw the stopiteration exception # Check if a function is a generator, yes, return true, no words return False# import inspect# ret  = inspect.isgeneratorfunction (MyGen) # print (ret) #查看生成器的当前状态 "" "There are several states:     1, gen_created: Is waiting for the first time to be executed     2, gen_running: currently being executed by the parser     3, Gen_ SUSPENDED: Wait for the next () call to Wake     4, gen_closed: Closed Run "" #测试一下, how to view theseImport inspectdef mygen2 of the State ():     yield 1gens = mygen2 () print ( Inspect.getgeneratorstate (gens)   #第一次查看状态是, gen_created (Waiting for first execution) print (Next (gens))   #通过next () Call Print (Inspect.getgeneratorstate (gens))   #此时的状态是GEN_SUSPENDED (wait for the next () call to wake up) try:     print (Next (gens))   #再next () once, because there is no value, a Stopiteration exception is thrown except stopiteration:     passprint (Inspect.getgeneratorstate (gens))   #那么, its status is gen_closed (closed run) #那么生成器的应用场景是啥? See an example "" In my Ubuntu OS environment [email protected]:~# ulimit -v 131072  #限制运行内存在128M [email  protected]:~# python3python 3.5.2  (default, nov 23 2017, 16:37:01)  [ gcc 5.4.0 20160609] on linuxtype  "Help",  "copyright",  "credits"  or   "License"  for more information.>>> a = list (range (10000000)) traceback  (Most recent call laST):  file  "<stdin>", line 1, in <module>memoryerror  #内存错误 >>>  #用生成器的方式试试 >>> for v in range (10000000):...      if v == 50000:...         print ("Found  ok ") ...          break... found ok strangely, I looked right at the left, It doesn't look like a generator! The reason is that:     in Python3, the range () function returns the generator, which means that an iterative object is returned (which must be remembered)      so, I only need the No. 50000 number, the generator will only generate 50,000 numbers, rather than just like      so try to generate 10 million numbers, causing the memory to burst I tested in the PYTHON2 environment, The questions to be aware of are: >>> xrange (10000000)   #python2中xrange是用于返回生成器 (that is, it will not be generated immediately and will be generated instantly when used) xrange ( 10000000) >>> range (10000000)   #range获取生成器 (that is, numbers are generated immediately) traceback  (most recent  Call last):  file  "<stdin>", line 1, in <module> Memoryerror Note: In the python3 to get rid of XThe range () function, with only a range in Range,python3, is a simple summary of the return generator, as the expert says:     Generator runs with very little memory consumption to handle large-scale datasets and loops with instant-generated values      any time you want to manipulate large-scale data, generators can help ensure that data is processed effectively "" "#再看一个例子 # General wording Def addlist (alist):    r = []    for i  In alist:        r.append (i + 1)      return rret = addlist ([1,2,3,4,5]) print (ret) #通过yield的写法def  yieldlist (alist):     for i in alist:        yield i  + 1ret1 = addlist ([1,2,3,4,5]) print (RET1) #结果都是一样, so the amount of data can not be underestimated what effect, or you do 10 million data you try again? And the effect came out. Finally, the difference between send and Next "" "Send () and next () is that send can pass parameters to the yield expression, and the passed argument will be the value of the yield expression, and the yield argument is the value returned to the caller. The initial call must first be next () or send (None), otherwise an error will be encountered. "" "#下面看个例子: I want to implement the production of some IP address, and send another function to work def jobs ():    while true:         ip = yield  #yiend接收send发送过来的ip         print ("ssh connection:{}, Start power off ... ". Format (IP))    #开始干活 # production IP address def production_ip ():     j = jobs ()     next (j)   #初始调用时必须先next ()     for  i in range (Ten):        ip =  "192.168.89. {0} ". Format (i)   #生产IP地址         j.send (IP)  # A function that takes an IP address to work jobsproduction_ip ()


python--a small test of the generator

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.