我有一些包含如下数据的数组:
a = np.random.rand(3,3)
b = np.random.rand(3,3)
使用 for 循环构造更大的矩阵
L = np.zeros((9,9))
for i in range(9):
for j in range(9):
L[i,j] = f(a,b,i,j) # values of L depends on values of a and b
稍后在我的程序中,我将更改 a 和 b,并且我希望我的 L 数组也更改。所以我的程序的逻辑看起来像这样(伪代码)
Create a
Create b
while True:
Create L using a and b
Do the stuff
Change a
Change b
在我的程序中,L 的大小很大(10^6 x 10^6 或更大)。 一次又一次地构造这个 L 矩阵是一个乏味且缓慢的过程。 我只想根据 a 和 b 的更改值更新 L 矩阵的值,而不是一次又一次地执行 for 循环。每次L的结构都是相同的,唯一的区别是单元格的值。像这样的事情:
a[0,0] = 2
b[0,0] = 2
L[3,5] = 2*a[0,0]*b[0,0]
L[3,5]
# >>> 8
a[0,0] = 3
b[0,0] = 1
# do some magic here
L[3,5]
>>> 6
最佳答案
这样的事情可以解决您的问题吗?
>>> a = 10
>>> b = 20
>>> def func():
# fetch the values of a and b
... return a+b
...
>>> lis = [func]
>>> lis[0]
<function func at 0x109f70730>
>>> lis[0]()
30
>>> a = 20
>>> lis[0]()
40
基本上每次通过调用函数获取值时 计算最新值。
关于python - 更新 numpy 数组中的值,无需繁琐的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53953798/