【发布时间】:2018-07-18 01:46:34
【问题描述】:
我试图通过切片和 for 循环修改列表中的值,但遇到了一些非常有趣的行为。如果有人可以在这里解释内部发生的事情,我将不胜感激。
>>> x = [1,2,3,4,5]
>>> x[:2] = [6,7] #slices can be modified
>>> x
[6, 7, 3, 4, 5]
>>> x[:2][0] = 8 #indices of slices cannot be modified
>>> x
[6, 7, 3, 4, 5]
>>> x[:2][:1] = [8] #slices of slices cannot be modified
>>> x
[6, 7, 3, 4, 5]
>>> for z in x: #this version of a for-loop cannot modify lists
... z += 1
...
>>> x
[6, 7, 3, 4, 5]
>>> for i in range(len(x)): #this version of a for-loop can modify lists
... x[i] += 1
...
>>> x
[7, 8, 4, 5, 6]
>>> y = x[:2] #if I assign a slice to a var, it can be modified...
>>> y[0] = 1
>>> y
[1, 8]
>>> x #...but it has no impact on the original list
[7, 8, 4, 5, 6]
【问题讨论】:
-
什么,究竟是你不明白?你期待什么?
-
但本质上,切片会创建副本,但 切片分配 会改变底层列表。由于
int对象是不可变的,z += 1只是简单的给变量z赋值一个新的列表,所以它等价于z = z + 1 -
切片和切片分配是有区别的。前者创建一个副本,后者进行特殊的
__setitem__调用。 See here. -
哇,我从没想过 Python 中的赋值如此复杂。感谢@Norrius 的链接,内容丰富。
标签: python python-3.x list for-loop slice