import numpy as np
A = np.array([[1, 1], [1, 2], [3, 1]])
B = np.array([[2, 3], [3, 2], [1, 4]])
C = np.array([[1, 2], [3, 4]])
# same shapes --> operations are not a problem
print(A+B)
print(A*B)
# shapes differ --> numpy raises ValueError
print(A+C)
print(A*C)
通過numpy的提出的ValueError異常是類似如下:
ValueError: operands could not be broadcast together with shapes (3,2) (2,2)
正如你所看到的,形狀由numpy
做任何陣列操作前檢查。
但是,如果你想這樣做手工或想趕上由numpy
引發的異常,你可以做這樣的事情:
# prevent numpy raising an ValueError by prooving array's shapes manually before desired operation
def multiply(arr1, arr2):
if arr1.shape == arr2.shape:
return arr1 * arr2
else:
print('Shapes are not equal. Operation cannot be done.')
print(multiply(A, B))
print(multiply(A, C))
# prevent numpy raising an ValueError by prooving array's shapes manually before desired operation
def add(arr1, arr2):
if arr1.shape == arr2.shape:
return arr1 + arr2
else:
print('Shapes are not equal. Operation cannot be done.')
print(add(A, B))
print(add(A, C))
# catch the error/exception raised by numpy and handle it like you want to
try:
result = A * C
except Exception as e:
print('Numpy raised an Exception (ValueError) which was caught by try except.')
else:
print(result)
...什麼?你想檢查尺寸?當你直接嘗試添加不等尺寸的數組時,numpy會拋出錯誤。 –
你可以試試'[EAFP](https://docs.python.org/3.5/glossary.html#term-eafp)'',你可能不知道它是什麼(還)。 –