我最近一直在尝试使用python生成器,我遇到以下好奇的行为,并且我很好奇为什么会发生这种情况以及发生了什么: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
旁白:如果你真的格式的整数,使用'%D','没有%s'。 – kojiro 2012-08-07 14:22:59
或者拥抱新的'format'语法。我第一次看到它时觉得有点长,但我越来越喜欢它。 – DSM 2012-08-07 14:29:49
作为一个同事曾经告诉我,*总是*%' – chepner 2012-08-07 14:29:59