输出背后的原因是什么?

问题描述 投票:1回答:1

输入

x, y = 20, 60
y, x, y = x, y-10, x+10
print(x, y)

输出

50 30

我期望什么

  • x = 20

  • y = 60

  • y = x = 20

  • x = y-10 = 20-10 = 10

  • y = x + 10 = 20

预期输出

10 20

为什么不是这种情况?是因为首先对表达式求值,然后才给变量赋值?

python-3.x output
1个回答
4
投票
右侧将进行完全评估,并在分配发生之前变成一个元组。所以你的代码:

x, y = 20, 60 y, x, y = x, y-10, x+10 print(x, y)

可以改写为:

r = (20, 60) x, y = r # x = 20, y = 60 r = (x, y-10, x+10) # r = (20, 50, 30) y, x, y = r # This line may lead to confusion # Tuple unpacking is done left to right so the line above is equivalent to: # y = 20 # x = 50 # y = 30 --> Note this overwrote the previous y assignment

因此

50 30


推荐问答