为什么传递数组副本仍会改变原始数组值?

时间:2017-05-13 19:33:02

标签: python arrays python-3.x

在下面的main方法中,

第一:我试图通过a.copy()b.copy()作为参数。虽然solve_linear_equations方法返回了有效的解决方案,但它仍然会篡改原始参数a[][]b[]

第二:然后,我尝试将两个不同的变量定义为tmp_a = a.copy()tmp_b = b.copy()。使用这些新变量作为方法参数也无济于事:通常,该方法会篡改原始数组值a[][]b[]

我认为,有一些关于Python内部的棘手问题我无法实现。任何人都能伸出援手吗?

import random


def data_create(n):
  a, x, b = [], [], []

  for i in range(n):
    a.append([])
    s = random.randint(0, 2)
    x.append(random.randint(0, 1000) / 1000)

    if s:
      x[i] *= -1

    for j in range(n):
      s = random.randint(0, 2)
      a[i].append(random.randint(0, 1000) / 1000)

      if s:
        a[i][j] *= -1

  for i in range(n):
    b.append(0.0)

    for j in range(n):
      b[i] += a[i][j] * x[j]

  return a, x, b


def solve_linear_equations(n, a, x):
  for i in range(n - 1):
    max_row = i
    max_val = abs(a[i][i])

    for j in range(i + 1, n):
      if abs(a[j][i]) > max_val:
        max_val = abs(a[j][i])
        max_row = j

    if max_row != i:
      x[i], x[max_row] = x[max_row], x[i]
      a[i], a[max_row] = a[max_row].copy(), a[i].copy()

    x[i] /= a[i][i]

    for j in range(i + 1, n):
      a[i][j] /= a[i][i]

    a[i][i] = 1.0

    for j in range(i + 1, n):
      x[j] -= x[i] * a[j][i]

      for k in range(i + 1, n):
        a[j][k] -= a[i][k] * a[j][i]

      a[j][i] = 0.0

  x[n - 1] /= a[n - 1][n - 1]
  a[n - 1][n - 1] = 1.0

  for i in range(n - 1, 0, -1):
    for j in range(i - 1, -1, -1):
      x[j] -= x[i] * a[j][i]

      for k in range(i, n):
        a[j][k] -= a[i][k] * a[j][i]

  return x


def main():
  n = 3
  a, x, b = data_create(n)

  print("x\n", x)
  print("a\n", a)
  print("b\n", b, "\n")

  tmp_a = a.copy() # creating a copy of a[][]
  tmp_b = b.copy() # creating a copy of b[]

  print("tmp_a\n", tmp_a)
  print("tmp_b\n", tmp_b, "\n")

  print("x\n", solve_linear_equations(n, tmp_a, tmp_b))
  print("a\n", a)
  print("b\n", b, "\n")


if __name__ == "__main__":
  main()

1 个答案:

答案 0 :(得分:4)

而不是

  tmp_a = a.copy() # creating a copy of a[][]
  tmp_b = b.copy() # creating a copy of b[]

DO

import copy
...
tmp_a = copy.deepcopy(a) # creating a deep copy of a[][]
tmp_b = copy.deepcopy(b) # creating a deep copy of b[]

这是因为list.copy()只降低了一级,你看到两个级别的不需要的更改。