你的linspace
看起来实际上可能是np.linspace
。如果是这样,你可以在不需要显式迭代的情况下操作numpy数组:
z = f(x[:, np.newaxis], y)
例如:
>>> import numpy as np
>>> x = np.linspace(0, 9, 10)
>>> y = np.linspace(0, 90, 10)
>>> x[:, np.newaxis] + y # or f(x[:, np.newaxis], y)
array([[ 0., 10., 20., 30., 40., 50., 60., 70., 80., 90.],
[ 1., 11., 21., 31., 41., 51., 61., 71., 81., 91.],
[ 2., 12., 22., 32., 42., 52., 62., 72., 82., 92.],
[ 3., 13., 23., 33., 43., 53., 63., 73., 83., 93.],
[ 4., 14., 24., 34., 44., 54., 64., 74., 84., 94.],
[ 5., 15., 25., 35., 45., 55., 65., 75., 85., 95.],
[ 6., 16., 26., 36., 46., 56., 66., 76., 86., 96.],
[ 7., 17., 27., 37., 47., 57., 67., 77., 87., 97.],
[ 8., 18., 28., 38., 48., 58., 68., 78., 88., 98.],
[ 9., 19., 29., 39., 49., 59., 69., 79., 89., 99.]])
但你也可以使用np.ogrid
代替两个linspace
:
import numpy as np
>>> x, y = np.ogrid[0:10, 0:100:10]
>>> x + y
array([[ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90],
[ 1, 11, 21, 31, 41, 51, 61, 71, 81, 91],
[ 2, 12, 22, 32, 42, 52, 62, 72, 82, 92],
[ 3, 13, 23, 33, 43, 53, 63, 73, 83, 93],
[ 4, 14, 24, 34, 44, 54, 64, 74, 84, 94],
[ 5, 15, 25, 35, 45, 55, 65, 75, 85, 95],
[ 6, 16, 26, 36, 46, 56, 66, 76, 86, 96],
[ 7, 17, 27, 37, 47, 57, 67, 77, 87, 97],
[ 8, 18, 28, 38, 48, 58, 68, 78, 88, 98],
[ 9, 19, 29, 39, 49, 59, 69, 79, 89, 99]])
这在一定程度上取决于你的f
。如果它包含像math.sin
这样的函数,则需要用numpy.sin
来替换它们。
如果与numpy
无关,则应该坚持使用您的选项或在循环时选择使用enumerate
:
for idx1, ai in enumerate(a):
for idx2, bj in enumerate(b):
z[idx1][idx2] = f(ai, bj)
这样做的好处是您不需要硬编码您的
range
(或
xrange
),也不需要使用
len(a)
作为输入。但是一般来说,如果没有巨大的性能差异
1 ,那么请使用您和其他人容易理解代码的方法。
1 如果你的 a
和 b
是 numpy.array
,那么性能差异会很大,因为如果不需要进行 list
<->numpy.array
转换,numpy 可以更快地处理数组。