Lin*_*ode 3 python memory variables
我将'haystack'保存在临时变量中,但是当我修改'haystack'时,临时变量也会改变.为什么?请帮忙?这是正常的?在PHP我没有这个问题.
# -*- coding:utf-8 -*-
haystack = [1,'Two',3]
tempList = haystack
print 'TempList='
print tempList
iterable = 'hello'
haystack.extend(iterable)
print 'TempList='
print tempList
Run Code Online (Sandbox Code Playgroud)
在控制台中返回
TempList=
[1, 'Two', 3]
TempList=
[1, 'Two', 3, 'h', 'e', 'l', 'l', 'o']
Run Code Online (Sandbox Code Playgroud)
但我没有修改变量'tempList'.
求救,谢谢.谢谢.
您没有创建列表的副本; 你只是创建了它的第二个引用.
如果要创建临时(浅)副本,请明确执行此操作:
tempList = list(haystack)
Run Code Online (Sandbox Code Playgroud)
或使用完整列表切片:
tempList = haystack[:]
Run Code Online (Sandbox Code Playgroud)
您在调用.extend()对象时就地修改了可变列表,因此对该列表的所有引用都将看到更改.
另一种方法是使用串联而不是扩展来创建新列表:
haystack = [1,'Two',3]
tempList = haystack # points to same list
haystack = haystack + list(iterable) # creates a *new* list object
Run Code Online (Sandbox Code Playgroud)
现在haystack变量已重新绑定到新列表; tempList仍然指旧列表.