Python 链式赋值问题

0
[已解决问题] 解决于 2024-06-29 23:35

``````>>> a, b, c = b, c, a = c, b, a = 1, 2, 3
>>> a, b, c
``````

``````(3, 2, 1)
``````

``````\$ python -m dis ./main.py
1           0 LOAD_CONST               0 ((1, 2, 3))
2 DUP_TOP
4 UNPACK_SEQUENCE          3
6 STORE_NAME               0 (a)
8 STORE_NAME               1 (b)
10 STORE_NAME               2 (c)
12 DUP_TOP
14 UNPACK_SEQUENCE          3
16 STORE_NAME               1 (b)
18 STORE_NAME               2 (c)
20 STORE_NAME               0 (a)
22 UNPACK_SEQUENCE          3
24 STORE_NAME               2 (c)
26 STORE_NAME               1 (b)
28 STORE_NAME               0 (a)

38 CALL_FUNCTION            3
40 POP_TOP
44 RETURN_VALUE
``````

``````a, b, c = 1, 2, 3
print(a, b, c)
``````

``````\$ python -m dis ./demo.py
1           0 LOAD_CONST               0 ((1, 2, 3))
2 UNPACK_SEQUENCE          3
4 STORE_NAME               0 (a)
6 STORE_NAME               1 (b)
8 STORE_NAME               2 (c)

18 CALL_FUNCTION            3
20 POP_TOP
24 RETURN_VALUE
``````

``````[3, 2, 1]
``````

``````[(1, 2, 3)]
``````

``````[(1, 2, 3), (1, 2, 3)]
``````

``````[(1, 2, 3), 3, 2, 1]
``````

a = 1

``````[(1, 2, 3), 3, 2]
``````

b = 2

``````[(1, 2, 3), 3]
``````

c = 3

``````[(1, 2, 3)]
``````

``````[(1, 2, 3), (1, 2, 3)]
``````

12 到 20 的操作大同小异，和上面基本差不多，此处略过。

``````[3, 2, 1]
``````

1

https://docs.python.org/3/reference/simple_stmts.html#assignment-statements
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

``````a, b, c = b, c, a = c, b, a = 1, 2, 3
#等同于
a, b, c = 1, 2, 3
b, c, a = 1, 2, 3
c, b, a = 1, 2, 3
``````

www378660084 | 小虾三级 |园豆：676 | 2024-06-29 15:12

0

damn ！我也摸不着头脑捏

cskaoyan王 | 园豆：202 (菜鸟二级) | 2024-06-29 08:53

您需要登录以后才能回答，未注册用户请先注册