【问题标题】:Is there a more pythonic way to write有没有更pythonic的写法
【发布时间】:2015-01-12 16:05:06
【问题描述】:

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

【问题讨论】:

  • @twasbrillig 发现了一个错误,包括更正 nmax -> nmax+1,然后我从错误应用的 mmax 中删除了 +1。
  • ...我添加了说明。 n=0 指的是 J0 等,请记住第一个零不是原点的零(对于 n>0)。

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


【解决方案1】:

“更 Pythonic”在这里的真正含义是什么。 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 毫秒对 1.77 毫秒),但可能不那么 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)。

【讨论】:

  • 感谢您的回答@ebarr。在十几个字符中从浮点数到布尔值再到整数非常酷! (提醒自己:这利用了 jn_zeros 的单调性)
猜你喜欢
  • 1970-01-01
  • 2020-05-08
  • 2018-10-06
  • 1970-01-01
  • 2010-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
相关资源
最近更新 更多