[Turn]python yield

Source: Internet
Author: User

  

Any function that uses yield is called a generator, such as:

Python code
    1. def count (N):
    2. While n > 0:
    3. yield n #生成值: n
    4. N-= 1

Another argument: The generator is a function that returns an iterator, and the difference from a normal function is that the generator contains a yield statement, and a simpler understanding of the generator is an iterator.

With yield, you can have the function generate a sequence that returns the object type "generator", through which successive calls to the next () method return a sequence value.

Python code
    1. c = Count (5)
    2. C.next ()
    3. >>> 5
    4. C.next ()
    5. >>>4

The generator function starts executing the statement inside the function only when the next () method is called, such as:

Python code
    1. def count (N):
    2. print "cunting"
    3. While n > 0:
    4. yield n #生成值: n
    5. N-= 1

When you call the Count function: C=count (5) does not print "counting" until you call C.next () to actually execute the statement inside. Each time the next () method is called, the Count function runs to the statement yield n , and the return value of next () is the generated value n , and when the next () method is called again, the The function continues to execute the statement after yield (a friend familiar with Java must know the Thread.yield () method, which is to pause the current thread's run and let other threads execute it), such as:

Python code
    1. def count (N):
    2. print "cunting"
    3. While n > 0:
    4. print ' before yield '
    5. yield n #生成值: n
    6. N-= 1
    7. print ' after yield '

The code above does not print "after yield" when the next method is called for the first time. If you call the next method all the time, when you execute to a value that has no iterations, the program will give you an error:

Traceback (most recent): File "", Line 1, in Stopiteration

Therefore, the next method is not normally called manually, and a For loop is used:

Python code
    1. For I in count (5):
    2. Print I,

Example: Using the yield generator to simulate commands in Linux: tail -f | grep python used to find lines in the monitoring log file that have Python words.

Python code
  1. Import time
  2. def tail (f):
  3. F.seek (0,2)#移动到文件EOF, reference: [Seek] (http://docs.python.org/2/library/stdtypes.html?highlight=file# File.seek)
  4. while True:
  5. line = F.readline () #读取文件中新的文本行
  6. if not line:
  7. Time.sleep (0.1)
  8. Continue
  9. yield Line
  10. def grep (Lines,searchtext):
  11. For line in lines:
  12. if SearchText in line:
  13. yield Line

Call:

Python code
    1. Flog = tail (open (' Warn.log '))
    2. Pylines = grep (flog,' python ')
    3. For line in Pylines:
    4. Print Line,

To achieve the Fibonacci sequence with yield:

Python code
    1. Def Fibonacci ():
    2. a=b=1
    3. yield a
    4. yield b
    5. while True:
    6. A, B = b,a+b
    7. yield b

Call:

Python code
    1. For num in Fibonacci ():
    2. if num > :
    3. Break
    4. Print num,

The effect of return in yield:
As a generator, because each iteration returns a value, it is not possible to return a value in the generator function, including the none value, or a "SyntaxError" exception is thrown, but a separate return can appear in the function, indicating that the statement ends.
Read the file continuously through a fixed-length buffer to prevent memory overflow in the case of a one-time read:

Python code
  1. def read_file (path):
  2. Size = 1024x768
  3. With open (path,' R ') as F:
  4. while True:
  5. block = F.read (SIZE)
  6. If block:
  7. yield Block
  8. Else:
  9. return

If you return a specific value in a function, you throw the exception directly.

Python code
    1. >>> def test_return ():
    2. ... yield 4
    3. ... return 0
    4. ...
    5. File "<stdin>", line 3
    6. SyntaxError: ' return ' with argument inside generator

Original address: Http://liuzhijun.iteye.com/blog/1852369#comments

[Turn]python yield

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.