要了解为什么我在程序中遇到错误(试图查找行列式的次要变量),我编写了一个简单的程序,因为变量被弄乱了。下面的该函数将2 * 2矩阵作为输入,并返回包含其行的列表(我知道这毫无意义,效率很低,但是我试图理解其背后的原理)。
To understand why I was getting an error in a program , in which I tried to find the "minor" of a determinant, I wrote a simpler program because my variables were messed up. This function below takes in a 2 * 2 matrix as an input, and returns a list containing its rows (pointless and inefficient, I know, but I'm trying to understand the theory behind this).
def alpha(A): #where A will be a 2 * 2 matrix B = A #the only purpose of B is to store the initial value of A, to retrieve it later mylist = [] for i in range(2): for j in range(2): del A[i][j] array.append(A) A = B return mylist但是,这里看来B是动态分配给A 的值,因为我无法将A的初始值存储在B中以便以后使用。为什么?
However, here it seems that B is assigned the value of A dynamically, in the sense that I'm not able to store the initial value of A in B to use it later. Why is that?
推荐答案因为python通过引用传递列表
Because python passes lists by reference
这意味着,当您写 b = a时,您说的是a和b是同一对象,并且当您更改b时,您也更改了a,反之亦然
This means that when you write "b=a" you're saying that a and b are the same object, and that when you change b you change also a, and viceversa
一种通过值复制列表的方法:
A way to copy a list by value:
new_list = old_list[:]如果列表中包含对象并且您也要复制它们,请使用通用copy.deepcopy():
If the list contains objects and you want to copy them as well, use generic copy.deepcopy():
import copy new_list = copy.deepcopy(old_list)更多推荐
按值复制列表列表,而不是引用
发布评论