本文介绍了复制变量改变原来的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有一个非常非常奇怪的简单问题.

I have a simple problem in Python that is very very strange.

def estExt(matriz,erro):
    # (1) Determinar o vector X das soluções
    print ("Matrix after:");
    print(matriz);

    aux=matriz;
    x=solucoes(aux); # IF aux is a copy of matrix, why the matrix is changed??

    print ("Matrix before: ");
    print(matriz)

...

如下所示,尽管 aux 被函数 solucoes()matriz 被改变了代码>.

As you see below, the matrix matriz is changed in spite of the fact that aux is the one being changed by the function solucoes().

之前的矩阵:
[[7, 8, 9, 24], [8, 9, 10, 27], [9, 10, 8, 27]]

矩阵之后:
[[[7, 8, 9, 24], [0.0, -0.14285714285714235, -0.2857142857142847, -0.42857142857142705],[0.0, 0.0, -3.0, -3.0000000000000018]]

推荐答案

aux=matriz;

不复制matriz,它只是创建一个名为aux 的对matriz 的新引用.你可能想要

Does not make a copy of matriz, it merely creates a new reference to matriz named aux. You probably want

aux=matriz[:]

假设 matriz 是一个简单的数据结构,这将创建一个副本.如果它更复杂,你应该使用 copy.deepcopy

Which will make a copy, assuming matriz is a simple data structure. If it is more complex, you should probably use copy.deepcopy

aux = copy.deepcopy(matriz)

顺便说一句,您不需要在每个语句后使用分号,python 不会将它们用作 EOL 标记.

As an aside, you don't need semi-colons after each statement, python doesn't use them as EOL markers.

这篇关于复制变量改变原来的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 12:41