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