Python-detailed explanation of yield usage

高洛峰
Release: 2016-10-19 11:43:56
Original
1299 people have browsed it

yield is simply a generator. A generator is a function that remembers the position in the function body when it last returned. The second (or nth) call to a generator function jumps to the middle of the function, leaving all local variables unchanged from the previous call.

The generator is a function

All parameters of the function will be retained

When this function is called for the second time

The parameters used are retained from the previous time.

The generator also "remembers" it in the flow control Constructing a

generator doesn’t just “remember” its data state. The generator also "remembers" its position within the flow control construct (in imperative programming, this construct is not just a data value). Continuity is still relatively general since it lets you jump arbitrarily between execution frames without always returning to the immediate caller's context (as with generators).

The operating mechanism of the yield generator

When you ask the generator for a number, the generator will execute until the yield statement appears. The generator will give you the parameters of yield, and then the generator will not continue to run. When you ask him for the next number, he will start running from the last state until the yield statement appears, give you the parameters, and then stop. Repeat this until the function exits.

Example: Python permutation, combination generator

#Generate full permutation

def perm(items, n=None):
    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
Copy after login

#Generate combination

def comb(items, n=None):
    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+1:]
            for c in comb(rest, n-1):
                yield v + c
  
a = perm('abc')
for b in a:
    print b
    break
print '-'*20
for b in a:
    print b
Copy after login

The results are as follows:

102 pvopf006 ~/test> ./generator.py

abc

--- ------------------

acb

bac

bca

cab

cba

As you can see, after the first loop break, the generator does not continue is executed, and the second loop is executed after the first loop


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template