按值复制列表列表,而不是引用

编程入门 行业动态 更新时间:2024-10-27 10:24:43
本文介绍了按值复制列表列表,而不是引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

按值复制列表列表,而不是引用

本文发布于:2023-11-08 13:22:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569484.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   而不是

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!