我最近一直在尝试使用 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