首页 > 解决方案 > 为多个元素赋值?

问题描述

我正在用 numpy 编写我的第一个代码。我想知道是否有一种更简单的方法可以为数组中的多个元素赋值,因为我对同一个数组多次使用相同的方程。

>>>ahp_c = np.ones(ahp_axis, dtype = np.float64)
[1., 1., 1., 1.]
[1., 1., 1., 1.]
[1., 1., 1., 1.]
[1., 1., 1., 1.]

>>>x = 1
>>>ahp_c[0][1] = (float(ps1) * x / x)
>>>ahp_c[1][0] = (x / float(ps1) * x)

>>>ahp_c[0][2] = (float(ps2) * x / x)
>>>ahp_c[2][0] = (x / float(ps2) * x)

>>>ahp_c[0][3] = (float(ps3) * x / x)
>>>ahp_c[3][0] = (x / float(ps3) * x)

>>>ahp_c[1][2] = (float(s1s2) * x / x)
>>>ahp_c[2][1] = (x / float(s1s2) * x)

>>>ahp_c[3][1] = (float(s1s3) * x / x)
>>>ahp_c[1][3] = (x / float(s1s3) * x)

>>>ahp_b[3][2] = (float(s2s3) * x / x)
>>>ahp_b[2][3] = (x / float(s2s3) * x)

[[1.         2.         3.         4.        ]
 [0.5        1.         0.2        6.        ]
 [0.33333333 5.         1.         7.        ]
 [0.25       0.16666667 0.14285714 1.        ]]

标签: pythonnumpyanaconda

解决方案


作为一个开始:

>>>ahp_c[0,1] = (float(ps1) * x / x)
>>>ahp_c[1,0] = (x / float(ps1) * x)

>>>ahp_c[0,2] = (float(ps2) * x / x)
>>>ahp_c[2,0] = (x / float(ps2) * x)

>>>ahp_c[0,3] = (float(ps3) * x / x)
>>>ahp_c[3,0] = (x / float(ps3) * x)

然后

ps = np.array([ps1,ps2,ps3], dtype=float)
x = 1.0
for i in range(0,3):
    ahp_c[0,i+1] = ps[i]*x/x
    ahp_c[i+1,0] = x/ps[i]*x

并继续:

ahp_c[0,1:] = ps*x/x
ahp_c[1:,0] = x/ps*x

使用 x/x looks odd, especially whenx=1`,但我关注的是多个语句,而不是数学。我试图找到一个通用模式,这样我们就不必使用显式索引,首先用循环替换它,然后用切片/范围索引。


推荐阅读