我最近对python生成器进行了一些试验,我遇到了以下奇怪的行为,我很想知道为什么会发生这种情况以及发生了什么:

def generating_test(n):
    for a in range(n):
        yield "a squared is %s" % a*a # Notice instead of a**2 we have written a*a

for asquare in generating_test(3):
    print asquare

输出:
a squared is 1
a squared is 2a squared is 2

与生成预期输出的以下脚本相比:
def generating_test(n):
    for a in range(n):
        yield "a squared is %s" % a**2 # we use the correct a**2 here

for asquare in generating_test(3):
    print asquare

输出:
a squared is 0
a squared is 1
a squared is 4

最佳答案

这与发电机无关:

>>> a = 2
>>> "a squared is %s" % a
'a squared is 2'
>>> ("a squared is %s" % a)*a
'a squared is 2a squared is 2'
>>> "a squared is %s" % a*a
'a squared is 2a squared is 2'
>>> "a squared is %s" % (a*a)
'a squared is 4'

使用字符串和第一个%作为参数,在乘法之前执行aop。你的a**2之所以有效,是因为在**之前对参数为a2%操作进行了评估。

08-25 20:26