python中可以同时给多个变量赋值,下面列举了三种方法
# Assign values directly
a, b = 0, 1
assert a == 0
assert b == 1
# Assign values from a list
(r,g,b) = ["Red","Green","Blue"]
assert r == "Red"
assert g == "Green"
assert b == "Blue"
# Assign values from a tuple
(x,y) = (1,2)
assert x == 1
assert y == 2
需要注意的地方:
a = 3
a, b = 1, a
如果按照正常的思维逻辑,先进行a = 1,在进行b = a,最后b等于1,但是这里b其实等于3,因为在连续赋值语句中等式右边其实都是局部变量,而不是真正的变量值本身,比如,上面例子中右边的a,在python解析的时候,只是把变量a的指向的变量3赋给b,而不是a=1之后a的结果