按值复制列表列表,而不是引用 [英] Copy a list of list by value and not reference

查看:60
本文介绍了按值复制列表列表,而不是引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要了解为什么我在程序中遇到错误(试图查找行列式的次要变量),我编写了一个简单的程序,因为变量被弄乱了。下面的该函数将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)

这篇关于按值复制列表列表,而不是引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆