【发布时间】:2012-08-07 14:10:12
【问题描述】:
我最近一直在尝试使用 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
【问题讨论】:
-
aside:如果您真的要格式化整数,请使用
%d,而不是%s。 -
或者采用新的
format语法。我第一次看到它时觉得它有点长,但我已经喜欢它了。 -
一位同事曾经告诉我,总是在 '%' 之后使用元组
-
@DSM 我同意
.format是最好的,无论如何每个人都应该使用它。
标签: python operator-precedence