![](/img/trans.png)
[英]Changing values of a numpy array using another array as a reference without loops
[英]Update values in numpy array without tedious for loops
我有一些数据这样的数组:
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矩阵的值。 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
基本上,每次您通过调用计算最新值的函数来获取值时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.