【问题标题】:Why is multiple assignment here giving unexpected results? [duplicate]为什么这里的多重赋值会产生意想不到的结果? [复制]
【发布时间】:2020-11-22 10:04:23
【问题描述】:

代码:

import numpy as np

def f(a):
    return np.array([0, 1])

N_x, N_y = 4, 3

U = V = np.zeros((N_x, N_y))

for n_y in range(N_y):
    for n_x in range(N_x):
        U[n_x, n_y], V[n_x, n_y] = f(0)

print(U, V)

这给出了意外的输出:

[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]] [[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

但是如果我使用

U = np.zeros((N_x, N_y))
V = np.zeros((N_x, N_y))

我得到以下预期结果,而不是 U = V = np.zeros((N_x, N_y))

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]] [[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

问题:这里出了什么问题?

【问题讨论】:

  • 在第一种情况下,您只有一个具有两个名称的数组,UV。在第二种情况下,您有两个不同的数组。
  • 在最新答案中查看我的评论。

标签: python arrays numpy


【解决方案1】:

通过多重赋值,您只会得到一个同时分配给 U 和 V 变量的对象,因此您可以有效地执行以下操作:

for n_y in range(N_y):
    for n_x in range(N_x):
        U[n_x, n_y], U[n_x, n_y] = f(0)

print(U, U)

【讨论】:

  • 那么为什么下面的工作? A = B = np.array([1]) A = np.array([0]) 这将按预期打印[0] [1]
  • 因为你将一个新对象分配给 A 变量(但 B 仍然指向第一个对象)。
猜你喜欢
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 2019-11-08
  • 1970-01-01
  • 2011-07-06
  • 2013-02-19
  • 2022-11-21
  • 1970-01-01
相关资源
最近更新 更多