输入:
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
为什么不是这种情况?是因为首先对表达式求值,然后才给变量赋值?
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