是否有更多的pythonic方式来编写

时间:2014-11-15 08:17:19

标签: arrays python-2.7 numpy scipy bessel-functions

在2.7中学习pythonic。有没有办法避免显式循环? answer = [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

1 个答案:

答案 0 :(得分:5)

&#34;更多Pythonic&#34;真的是这里的意思Python的核心原则之一是可读性,因此如果没有真正的性能理由去除循环,那就保留它们。

如果你真的想看到其他一些方法来做同样的事情,那么:

z = np.zeros((nmax+1, mmax))
for i in range(nmax+1):
    z[i] = spe.jn_zeros(i, mmax)

可以替换为:

func = lambda i:spe.jn_zeros(i,mmax)
np.vstack(np.vectorize(func, otypes=[np.ndarray])(np.arange(nmax+1)))

略快(1.35 ms vs. 1.77 ms)但可能更少Pythonic和

[np.max(np.where(z[i]<big))+1 for i in range(nmax+1)]

可以替换为

np.cumsum(z < big,axis=1)[:,-1]

我认为它更像Pythonic(或numpythonic)并且速度更快(20 us vs. 212 us)。