我必须在Python中为我正在做的项目制作拉格朗日多项式.我正在做一个重心的样式,以避免使用显式的for循环而不是Newton的分割差异样式.我遇到的问题是我需要将除法除以零,但Python(或者可能是numpy)只是使它成为警告而不是正常的异常.
所以,我需要知道的是抓住这个警告,好像它是一个例外.我在本网站上发现的相关问题没有按照我需要的方式回答.这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
import warnings
class Lagrange:
    def __init__(self, xPts, yPts):
        self.xPts = np.array(xPts)
        self.yPts = np.array(yPts)
        self.degree = len(xPts)-1 
        self.weights = np.array([np.product([x_j - x_i for x_j in xPts if x_j != x_i]) for x_i in xPts])
    def __call__(self, x):
        warnings.filterwarnings("error")
        try:
            bigNumerator = np.product(x - self.xPts)
            numerators = np.array([bigNumerator/(x - x_j) for x_j in self.xPts])
            return sum(numerators/self.weights*self.yPts) 
        except Exception, e: # Catch division by 0. Only possible in 'numerators' array
            return yPts[np.where(xPts …我不想将非元组序列用于多维索引,以便脚本在此更改时支持Python的未来版本.
下面是我用于绘制图形的代码:
data = np.genfromtxt(Example.csv,delimiter=',', dtype=None, names=True, 
    converters={0: str2date})
p1, = host.plot(data["column_1"], data["column_2"], "b-", label="column_2")
p2, = par1.plot(data["column_1"], data['column_3'], "r-", label="column_3")
p3, = par2.plot(data["column_1"], data["column_4"], "g-", label="column_4")
host.set_xlim([data["column_1"][0], data["column_1"][-1]])
host.set_ylim(data["column_2"].min(), data["column_2"].max())
par1.set_ylim(data["column_3"].min(), data["column_3"].max())
par2.set_ylim(data["column_4"].min(), data["column_4"].max())
(使用Python 3.1)
我知道这个问题已经问过很多关于测试迭代器是否为空的一般问题了。显然,没有解决方案(我想是有原因的-迭代器直到被要求返回下一个值才真正知道它是否为空)。
但是,我有一个特定的示例,希望我可以用它编写干净的Pythonic代码:
#lst is an arbitrary iterable
#f must return the smallest non-zero element, or return None if empty
def f(lst):
  flt = filter(lambda x : x is not None and x != 0, lst)
  if # somehow check that flt is empty
    return None
  return min(flt)
有什么更好的方法吗?
编辑:抱歉的愚蠢表示法。函数的参数确实是一个任意可迭代的,而不是列表。
python ×3
numpy ×2
python-3.x ×2
arrays ×1
exception ×1
filter ×1
iterable ×1
iterator ×1
matplotlib ×1
warnings ×1