将函数应用于数组
applying function to array
Python 新手,我正在努力寻找在数组上应用函数的正确习惯用法。
我想计算从 -1 到 1 的相关勒让德多项式,
import scipy.special as sc
m = 0
n = 2
z = 0.5
sc.lpmn(m, n, z)
这一切都很好,但是函数没有在 z 上向量化。我如何(有效地)将它应用到值数组?这是我尝试使用理解,假设我需要以一种或另一种方式循环
import numpy as np
z = np.linspace(-1,1,20)
result = [sc.lpmn(0, 2, z[i])[0][0] for i in enumerate(z)]
它比那更简单,我认为没有理由使用枚举。以下代码应该足够了:
import scipy.special as sc
z = np.linspace(-1,1,20)
result = [sc.lpmn(0, 2, i)[0][0] for i in z]
输出为:
[array([ 1., -1., 1.]),
array([ 1. , -0.89473684, 0.70083102]),
array([ 1. , -0.78947368, 0.43490305]),
array([ 1. , -0.68421053, 0.20221607]),
array([ 1. , -0.57894737, 0.00277008]),
array([ 1. , -0.47368421, -0.1634349 ]),
array([ 1. , -0.36842105, -0.29639889]),
array([ 1. , -0.26315789, -0.39612188]),
array([ 1. , -0.15789474, -0.46260388]),
array([ 1. , -0.05263158, -0.49584488]),
array([ 1. , 0.05263158, -0.49584488]),
array([ 1. , 0.15789474, -0.46260388]),
array([ 1. , 0.26315789, -0.39612188]),
array([ 1. , 0.36842105, -0.29639889]),
array([ 1. , 0.47368421, -0.1634349 ]),
array([1. , 0.57894737, 0.00277008]),
array([1. , 0.68421053, 0.20221607]),
array([1. , 0.78947368, 0.43490305]),
array([1. , 0.89473684, 0.70083102]),
array([1., 1., 1.])]
Python 新手,我正在努力寻找在数组上应用函数的正确习惯用法。
我想计算从 -1 到 1 的相关勒让德多项式,
import scipy.special as sc
m = 0
n = 2
z = 0.5
sc.lpmn(m, n, z)
这一切都很好,但是函数没有在 z 上向量化。我如何(有效地)将它应用到值数组?这是我尝试使用理解,假设我需要以一种或另一种方式循环
import numpy as np
z = np.linspace(-1,1,20)
result = [sc.lpmn(0, 2, z[i])[0][0] for i in enumerate(z)]
它比那更简单,我认为没有理由使用枚举。以下代码应该足够了:
import scipy.special as sc
z = np.linspace(-1,1,20)
result = [sc.lpmn(0, 2, i)[0][0] for i in z]
输出为:
[array([ 1., -1., 1.]),
array([ 1. , -0.89473684, 0.70083102]),
array([ 1. , -0.78947368, 0.43490305]),
array([ 1. , -0.68421053, 0.20221607]),
array([ 1. , -0.57894737, 0.00277008]),
array([ 1. , -0.47368421, -0.1634349 ]),
array([ 1. , -0.36842105, -0.29639889]),
array([ 1. , -0.26315789, -0.39612188]),
array([ 1. , -0.15789474, -0.46260388]),
array([ 1. , -0.05263158, -0.49584488]),
array([ 1. , 0.05263158, -0.49584488]),
array([ 1. , 0.15789474, -0.46260388]),
array([ 1. , 0.26315789, -0.39612188]),
array([ 1. , 0.36842105, -0.29639889]),
array([ 1. , 0.47368421, -0.1634349 ]),
array([1. , 0.57894737, 0.00277008]),
array([1. , 0.68421053, 0.20221607]),
array([1. , 0.78947368, 0.43490305]),
array([1. , 0.89473684, 0.70083102]),
array([1., 1., 1.])]