您可以更改顺序,它会起作用:
l1=[0,2,1]
index=1
l1[l1[index]], l1[index] = l1[index], l1[l1[index]]
print(l1)
Output:
[0, 1, 2]
因此,让我们首先看看代码的反汇编:
import dis
def switch():
l1=[0,2,1]
index=1
l1[index], l1[l1[index]] = l1[l1[index]], l1[index]
return l1
dis.dis(switch)
2 0 LOAD_CONST 1 (0)
2 LOAD_CONST 2 (2)
4 LOAD_CONST 3 (1)
6 BUILD_LIST 3
8 STORE_FAST 0 (l1)
3 10 LOAD_CONST 3 (1)
12 STORE_FAST 1 (index)
5 14 LOAD_FAST 0 (l1)
16 LOAD_FAST 0 (l1)
18 LOAD_FAST 1 (index)
20 BINARY_SUBSCR
22 BINARY_SUBSCR
24 LOAD_FAST 0 (l1)
26 LOAD_FAST 1 (index)
28 BINARY_SUBSCR
30 ROT_TWO
32 LOAD_FAST 0 (l1)
34 LOAD_FAST 1 (index)
36 STORE_SUBSCR
38 LOAD_FAST 0 (l1)
40 LOAD_FAST 0 (l1)
42 LOAD_FAST 1 (index)
44 BINARY_SUBSCR
46 STORE_SUBSCR
6 48 LOAD_FAST 0 (l1)
50 RETURN_VALUE
在这种类型的赋值中,首先计算表达式的右侧(请参阅评估顺序 https://docs.python.org/3/reference/expressions.html#evaluation-order)。首先,指令集(14 - 18)
loads l1[index]
, i.e. 1
,并将其压入堆栈。然后,24-26
loads l1[l1[index]]
, i.e. 2
并将其推入堆栈。所以堆栈现在保存[2,1]
. ROT_TWO(30) https://docs.python.org/2/library/dis.html#opcode-ROT_TWO交换堆栈并使其[1, 2]
,我们想要的顺序。
现在,在 32 - 36 中,堆栈的顶部,即1
被分配给l1[index]
,所以现在,l1[index] == 1
, i.e. l1[1] = 1
.
然后 38 - 42,栈中剩余的元素,即2
被弹出到l1[l1[index]]
,但现在的值l1[index]
是 1,所以你本质上是在做,l1[1] = 1
。那么让我们看看:
l1[index], l1[l1[index]] = l1[l1[index]], l1[index]
loaded == 2, 1
after stack swapping == 1, 2
l1[1] == 1
l1[1] == 2
# So you have modified only index 1, and then overwritten it with its original value.
像这样的事情:
14 LOAD_FAST 0 (l1) ¯¯|
16 LOAD_FAST 0 (l1) ¯¯| 2 | 1 ---------->
18 LOAD_FAST 1 (index)__| __| ↓
20 BINARY_SUBSCR |
22 BINARY_SUBSCR |
24 LOAD_FAST 0 (l1) ¯¯| 2 ------------------------>
26 LOAD_FAST 1 (index)__| | ↓
28 BINARY_SUBSCR | |
30 ROT_TWO | |
32 LOAD_FAST 0 (l1) ¯¯| ↓ |
34 LOAD_FAST 1 (index)__| l1[1] = 1 <-------- |
36 STORE_SUBSCR | |
38 LOAD_FAST 0 (l1) | ¯¯| |
40 LOAD_FAST 0 (l1) ¯¯| ↓ | |
42 LOAD_FAST 1 (index)__| l1[1] == 1 __| l1[1] = 2 <---
44 BINARY_SUBSCR
46 STORE_SUBSCR
如果我们在我的解决方案中遵循相同的推理:
l1[l1[index]], l1[index] = l1[index], l1[l1[index]]
loaded = 1, 2
after stack swapping == 2, 1
l1[2] = 2
l1[1] = 1
# Here, as you have not changed the value of `l1[index]` in the first assignment, the order remains.
现在您可以遵循相同的逻辑l1 = [0, 1, 2]
。虽然不需要解释,因为两者l1[index]
and l1[l1[index]]
是相同的:
l1 = [0, 1, 2]
l1[index], l1[l1[index]] = l1[l1[index]], l1[index]
loaded = 1, 1
after stack swapping == 1, 1
l1[1] == 1
l1[1] == 1
------------------------------------------------------------------
l1[l1[index]], l1[index] = l1[index], l1[l1[index]]
loaded = 1, 1
after stack swapping == 1, 1
l1[1] = 1
l1[1] = 1
# Here both have same value, so it does not modify.
因此,当您通过传递列表元素作为索引来访问索引时,最好避免这种分配。相反,应该Explicit https://www.python.org/dev/peps/pep-0020/:
l1 = [0, 2, 1]
index1 = 1
index2 = l1[index1]
l1[index1], l1[index2] = l1[index2], l1[index1]
print(l1)
# [0, 1, 2]