使用append方法实现Python浅拷贝和深拷贝
在python3.5中使用append方法会出现一些问题。给出了代码使用append方法实现Python浅拷贝和深拷贝,python,python-3.x,copy,deep-copy,Python,Python 3.x,Copy,Deep Copy,在python3.5中使用append方法会出现一些问题。给出了代码 # generate boson basis in lexicographic order def boson_basis(L,N): basis=[] state=[0 for i in range(1,L+1)] pos=0 # initialize the state to |N,0,...,0> state[0]=N basis.append(state) # find the first non-zero po
# generate boson basis in lexicographic order
def boson_basis(L,N):
basis=[]
state=[0 for i in range(1,L+1)]
pos=0
# initialize the state to |N,0,...,0>
state[0]=N
basis.append(state)
# find the first non-zero position in reverse order
while state[L-1]<N:
for i in range(-2,-L-1,-1):
if state[i]>0:
pos=L+i
break
sum=0
for i in range(0,pos):
sum=sum+state[i]
state[pos]=state[pos]-1
state[pos+1]=N-sum-state[pos]
basis.append(state)
return basis
result=boson_basis(3,3)
将
x
更改为x=5
后,b
保持不变b=[3]
。它确实让我感到困惑,似乎与前一个例子相矛盾。正如前面的评论所揭示的那样,追加操作中没有任何副本。
因此,您必须自己明确地处理此问题,例如,通过替换
basis.append(state)
与
使用:
的切片操作将创建状态的副本。
注意:它不会复制列表元素,但只要列表中只保留普通数字而不保留对象,就可以了。阅读不可变对象和可变对象,以及按值传递和按引用传递,Append不会复制任何内容,这就是为什么列表中多次出现相同的列表。
basis.append(state)
basis.append(state[:])