0

我试图减去两个零排名的numpy数组a和b。我希望 ab 在大小不同时返回错误。例如,如果 shape(a)=[300,] 并且 shape(b)=[450,]; ab 返回一个 shape[300,450] 的数组。相反,我希望程序返回错误。

4

2 回答 2

1

您可以尝试这种方法:

def mySubtract(a, b):
    if a is None or b is None or a.shape != b.shape:
       sys.stderr.write("a and b don't have the same shape!\n")
       raise ValueError("a and b don't have same shape!")
    return a-b

我不确定您所说的“返回错误”是什么意思,但是如果您更愿意只返回无效结果而不是引发 ValueError 异常,则可以改为使用return Noneor return "a and b don't have the same shape!"

请记住,您的例程的调用者需要知道如何处理这些特殊的错误返回代码。所以一般来说例外可能是一种更清洁的方法。

于 2013-07-14T21:47:26.103 回答
0

您可能想查看异常情况。下面是一些伪代码,应该可以为您指明正确的方向:

if a.size() != b.size():
    raise Exception("Invalid sizes")
于 2013-07-14T21:40:01.090 回答