Pythonyield summary and examples

Source: Internet
Author: User
Yield is used to convert a function into a generator. a function with yield is no longer a common function, the Python interpreter regards it as a generator (I don't know what a generator is. I want to understand Python's generator first). a function with yield is a generator, which is different from a common function, generate a generator that looks like a function call, but does not execute any function code until next () is called for it (next () is automatically called in the for loop. Although the execution process is still executed according to the function process, every execution of a yield statement is interrupted and an iteration value is returned. the next statement of yield continues to be executed during the next execution. It seems that a function is interrupted several times by yield during normal execution, and the current iteration value is returned through yield for each interruption.

Benefits of yield:By rewriting a function as a generator, the iteration capability is obtained. compared to calculating the next () value by using the instance storage status of the class, the code is concise and the execution process is abnormal and clear.

Test code:

The code is as follows:


#! /Usr/bin/env python
#-*-Coding: utf8 -*-

Def fab (max ):
"Fibonacci data column """
N, a, B = 0, 0, 1
While n <max:
Yield B
A, B = B, a + B
N + = 1


Def perm (items, n = None ):
"Full sorting """
If n is None:
N = len (items)
For I in range (len (items )):
V = items [I: I + 1]
If n = 1:
Yield v
Else:
Rest = items [: I] + items [I + 1:]
For p in perm (rest, n-1 ):
Yield v + p

If _ name _ = '_ main __':
For n in fab (5 ):
Print n
Print "full arrangement: 123"
For n in perm ("123 "):
Print n

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.