简体   繁体   English

Python生成器

[英]Python generators

I have problems understanding how this generator works. 我在理解此生成器的工作方式时遇到问题。 How exactly does it create permutations? 它如何精确地创建排列? Also, in the code, what does yield[items[i]] + cc yield and to where? 另外,在代码中, yield[items[i]] + cc结果是什么? What is added to the list yield[] each time yield[items[i]] + cc is called? 每次调用yield[items[i]] + cc时,会在列表yield[]添加什么? (is anything even added?) i'm sorry but I'm really confused:( (还添加了什么吗?)对不起,但我真的很困惑:(

sorry for such a novice question and I hope someone could help me understand this better! 对于这样的新手问题,我们深表歉意,希望有人能帮助我更好地理解这一点! Thanks! 谢谢!

def permutations(items):

    n = len
    if n == 0:
        yield[]
    else:
        for i in range(len(items)):
           for cc in permutations(items[:i] + items[i+1:]:
               yield[items[i]] + cc
for p in permutations(['r','e','d']):
    print ''.join(p)

yield is a statement, like print or return . yield是一个语句,例如printreturn

imagine that you have a function: 假设您有一个功能:

def blah(x):
    return x
    return x + 1
    return x + 2
    return x + 3

and then you call it: 然后您将其称为:

print blah(10)

it will only return 10, and it will never get to 11, 12, or 13, as the function is finished. 函数完成后,它只会返回10,并且永远不会达到11、12或13。

when you use yield, you are essentially saying, "pretend this function is a list..." and then the yield statement is used from the function to return one value after another, until it's run out, instead of returning just one value. 当使用yield时,您实际上是在说:“假装此函数为列表...”,然后使用yield语句从该函数开始依次返回一个值,直到用完为止,而不是仅返回一个值。

so: 所以:

def gen_blah(x):
    yield x
    yield x+1
    yield x+2
    yield x+3

for i in gen_blah(10):
    print i

will print 10 then 11, 12 and 13. 将先打印10,然后打印11、12和13。

So the permutations function is yielding each of the values one at a time, which then the for loop outside of the generator function is using. 因此,置换函数一次产生每个值,然后在生成器函数外部使用for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM