求问Python的一个列表赋值问题

为什么

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]

阅读 4.9k
6 个回答

根据 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)会产生语法错误,赋值语句没有值.

参考 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]

看结果反推,是i=3 在 s[i] = 3之前执行了。

你就分开两句写不行吗?

可使用 PythonTutor.com
i = s[i] = 3 那一行基本上就是先後執行i=3 及s[i]=3

clipboard.png

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
>>> 
推荐问题
宣传栏