gpt4 book ai didi

Python - 奇怪/意外的行为 - 运算符的优先级

转载 作者:太空狗 更新时间:2023-10-29 21:12:50 25 4
gpt4 key购买 nike

我最近对 ​​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'

% 运算在乘法之前执行,使用字符串和第一个 a 作为参数。您的 a**2 之所以有效,是因为以 a2 作为参数的 ** op 在 %

关于Python - 奇怪/意外的行为 - 运算符的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11847848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com