為什麼
s = [1, 2, 3, 4, 5, 6]
i = 0
i = s[i] = 3
結果是: [1, 2, 3, 3, 5, 6] 而非[3, 2, 3, 4, 5, 6]
扔个三星炸死你2017-06-12 09:26:18
根據 Assignment statements 可知:
a = b = c = d = ... = E
等同於
a = E
b = E
c = E
d = E
...
所以: i=s[i]=3
等同於:
i = 3
s[i] = 3
Python 中的賦值是一個語句,並不是一個操作子,所以表達式(a=b)
會產生語法錯誤,賦值語句沒有值.
怪我咯2017-06-12 09:26:18
參考 https://stackoverflow.com/que...
等同於
s = [1, 2, 3, 4, 5, 6]
i = 0
temp_value = 3
i = temp_value
s[i] = temp_value
首先是i變成了3,然後才賦值s[i]
typecho2017-06-12 09:26:18
i = s[i] = 3
等價於 i = 3; s[i] = 3
用dis模組來解析執行過程:
>>> def f():
s = [1, 2, 3, 4, 5, 6]
i = 0
i = s[i] = 3
>>> import dis
>>> dis.dis(f)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 LOAD_CONST 4 (4)
12 LOAD_CONST 5 (5)
15 LOAD_CONST 6 (6)
18 BUILD_LIST 6
21 STORE_FAST 0 (s) # s = [1, 2, 3, 4, 5, 6]
3 24 LOAD_CONST 7 (0)
27 STORE_FAST 1 (i) # i = 0
4 30 LOAD_CONST 3 (3) # 常量3 入栈
33 DUP_TOP # 复制栈顶,也就是 常量3
34 STORE_FAST 1 (i) # i = 3
37 LOAD_FAST 0 (s)
40 LOAD_FAST 1 (i)
43 STORE_SUBSCR # s[i] = 3
44 LOAD_CONST 0 (None) # 返回 None
47 RETURN_VALUE
分開寫的範例
>>> def f2():
s = [1, 2, 3, 4, 5, 6]
i = 0
i = 3
s[i] = 3
>>> dis.dis(f2)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 LOAD_CONST 4 (4)
12 LOAD_CONST 5 (5)
15 LOAD_CONST 6 (6)
18 BUILD_LIST 6
21 STORE_FAST 0 (s) # s = [1, 2, 3, 4, 5, 6]
3 24 LOAD_CONST 7 (0)
27 STORE_FAST 1 (i) # i = 0
4 30 LOAD_CONST 3 (3)
33 STORE_FAST 1 (i) # i = 3
5 36 LOAD_CONST 3 (3)
39 LOAD_FAST 0 (s)
42 LOAD_FAST 1 (i)
45 STORE_SUBSCR # s[i] = 3
46 LOAD_CONST 0 (None)
49 RETURN_VALUE
>>>