更新numpy数组中的值而无需繁琐的for循环

时间:2018-12-28 04:49:10

标签: python arrays numpy

我有一些数组,像这样:

a = np.random.rand(3,3)
b = np.random.rand(3,3)

使用循环,我构造了更大的矩阵

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

1 个答案:

答案 0 :(得分:0)

类似的东西可以解决您的问题吗?

>>> 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

基本上,每次您通过调用函数获取值时 计算最新值。