如何调用列表(Case 1
)的属性,使print y
的输出与Case 2
不同?
# Case 1: using a list as value
>>> x = ["one", "two", "three"]
>>> y = x
>>> x[0] = "four"
>>> print x
["four", "two", "three"]
>>> print y
["four", "two", "three"]
# Case 2: using an integer as value
>>> x = 3
>>> y = x
>>> x = x + 1
>>> print x
4
>>> print y
3
修改:
为了表明此行为与可变列表和字符串无关,而不是案例2,可能会给出以下情况:
>>> x = ["one", "two", "three"]
>>> y = x
>>> x = x + ["four", "five"]
>>> print x
["four", "two", "three", "four", "five"]
>>> print y
["four", "two", "three"]
答案 0 :(得分:2)
两个片段之间的主要区别是
>>> x[0] = "four"
VS
>>> x = x + 1
在第一种情况下,您修改现有对象,在第二种情况下创建一个新对象。所以第一个片段有一个对象和两个名称,x和y,引用它,在第二个片段中有两个对象。请注意,这与列表的可变性(以及整体的 immutability )无关,您可以将第二个代码段写为
x = [1,2,3]
y = x
x = x + [4]
并获得基本相同的结果(=两个不同的对象)。