如何创建将列表元素作为参数绘制函数的函数

时间:2018-08-27 00:55:28

标签: python python-3.x numpy

我写了以下代码:

m = np.arange(-5, 5, 0.1)
q = np.arange(-500, 500, 0.1)
m, q = np.meshgrid(m, q)

接下来,说:

a = [[1,2],[2,3]]

我想要:

y = np.sqrt((a[0][0]*m + q - a[0][1])**2 + (a[1][0]*m + q - a[1][1])**2)

但是我想写成:

y = np.sqrt((x[0]*m + q - x[1])**2 + (x[0]*m + q - x[1])**2)

其中a中的x,(第一种情况下x = [1,2],x = [2,3])

总的来说,我正在寻找一种将其概括的方法,以便可以编写如下内容:

y = np.sqrt(sum((m*x[0]+q - x[1])**2 for x in a))

我该怎么做?

(在特定示例中,它应该返回,但它需要对两个数字列表中的a起作用): y = np.sqrt((1 * m + q-2)** 2 +(2 * m + q-3)** 2)

编辑:

y = np.sqrt(sum((m*x[0]+q - x[1])**2 for x in a))

实际上是正确的代码,我的错误是在其他地方。

2 个答案:

答案 0 :(得分:0)

您可以完全按照您的描述

>>> def y(x):
...     return np.sqrt((x[0]*m + q - x[1])**2 + (x[0]*m + q - x[1])**2)
>>> y(a[0])
array([[ 717.00627612,  716.86485477,  716.72343341, ...,  703.28840457,
         703.14698321,  703.00556186],
       [ 716.86485477,  716.72343341,  716.58201205, ...,  703.14698321,
         703.00556186,  702.8641405 ],
       [ 716.72343341,  716.58201205,  716.4405907 , ...,  703.00556186,
         702.8641405 ,  702.72271914],
       ..., 
       [ 696.78302218,  696.92444354,  697.06586489, ...,  710.50089374,
         710.64231509,  710.78373645],
       [ 696.92444354,  697.06586489,  697.20728625, ...,  710.64231509,
         710.78373645,  710.92515781],
       [ 697.06586489,  697.20728625,  697.34870761, ...,  710.78373645,
         710.92515781,  711.06657916]])
>>> y(a[1])
array([[ 725.4915575 ,  725.20871478,  724.92587207, ...,  698.05581439,
         697.77297167,  697.49012896],
       [ 725.35013614,  725.06729343,  724.78445072, ...,  697.91439303,
         697.63155032,  697.34870761],
       [ 725.20871478,  724.92587207,  724.64302936, ...,  697.77297167,
         697.49012896,  697.20728625],
       ..., 
       [ 688.29774081,  688.58058352,  688.86342623, ...,  715.73348392,
         716.01632663,  716.29916934],
       [ 688.43916216,  688.72200488,  689.00484759, ...,  715.87490527,
         716.15774799,  716.4405907 ],
       [ 688.58058352,  688.86342623,  689.14626894, ...,  716.01632663,
         716.29916934,  716.58201205]])

>>> Y = [y(x) for x in a]
>>> for yy in Y: 
...     print('do something')

答案 1 :(得分:0)

尝试

m = np.arange(-5, 5, 0.1)
q = np.arange(-500, 500, 0.1)
m, q = np.meshgrid(m, q)

a = np.array([[1,2],[2,3]])

y = np.sqrt(np.power(m[..., np.newaxis] * a[:, 0] + q[..., np.newaxis] - a[:, 1], 2).sum(axis=-1))