我编写了一个简单的函数来使用numpy对我的频谱做基线减运算。代码如下所示:
import numpy as np
def bas_sub(baseline_y, spectrum_y):
try:
len(baseline_y)==len(spectrum_y)
spectrum_new = np.copy(spectrum_y)-baseline_y
return spectrum_new
except:
print 'Baseline and spectrum shoud have the same length.'
其中基线和频谱是两个一维numpy阵列。我希望我的函数做一个简单的长度检查,也就是说,如果基线和频谱有不同的长度,函数应该打印消息:“基线和频谱应该具有相同的长度”。该函数适用于等长输入,但不能打印不同长度输入的消息。在最后一种情况下,函数输出是一个NoneType对象。我做错什么了?谢谢
发布于 2015-11-02 13:55:09
另一种方法是使用断言:
import numpy as np
def bas_sub(baseline_y, spectrum_y):
assert len(baseline_y)==len(spectrum_y), "Baseline and spectrum shoud have the same length."
spectrum_new = np.copy(spectrum_y)-baseline_y
return spectrum_new
发布于 2015-11-02 13:28:12
除了阻塞,没有任何东西会抛出异常以被捕获。
在这里,异常处理不是正确的模式。您应该只使用if/else语句:
def bas_sub(baseline_y, spectrum_y):
if len(baseline_y) == len(spectrum_y):
spectrum_new = np.copy(spectrum_y) - baseline_y
return spectrum_new
else:
print 'Baseline and spectrum shoud have the same length.'
https://stackoverflow.com/questions/33478687
复制相似问题