uho*_*hoh 1 arrays numpy scipy bessel-functions python-2.7
在2.7中学习pythonic.有没有办法避免显式循环?回答=[5, 4, 4, 3, 3, 2]
import numpy as np
import scipy.special as spe
nmax = 5 # n = 0, 1 ...5
mmax = 7 # m = 1, 2 ...7
big = 15.
z = np.zeros((nmax+1, mmax))
for i in range(nmax+1):
z[i] = spe.jn_zeros(i, mmax)
answer = [np.max(np.where(z[i]<big))+1 for i in range(nmax+1)]
print answer # list of the largest m for each n where the mth zero of Jn < big
Run Code Online (Sandbox Code Playgroud)
什么"更多Pythonic"在这里真正意味着什么.一个Python的核心原则是可读性,因此,如果没有真正的业绩的原因摆脱循环的,只是让他们.
如果你真的想看到其他一些方法来做同样的事情,那么:
z = np.zeros((nmax+1, mmax))
for i in range(nmax+1):
z[i] = spe.jn_zeros(i, mmax)
Run Code Online (Sandbox Code Playgroud)
可以替换为:
func = lambda i:spe.jn_zeros(i,mmax)
np.vstack(np.vectorize(func, otypes=[np.ndarray])(np.arange(nmax+1)))
Run Code Online (Sandbox Code Playgroud)
这稍快一点(1.35毫秒对1.77毫秒),但可能更少Pythonic和
[np.max(np.where(z[i]<big))+1 for i in range(nmax+1)]
Run Code Online (Sandbox Code Playgroud)
可以替换为
np.cumsum(z < big,axis=1)[:,-1]
Run Code Online (Sandbox Code Playgroud)
我认为它更像Pythonic(或numpythonic)并且速度更快(20 us vs. 212 us).
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |