Python:如何检查是否可以添加两个数组?

Ame*_*one 0 python numpy

# *-* coding: utf-8 *-*

import numpy as np
import scipy as sc

A = np.array([[1,1], [1,2], [3,1]])
B = np.array([[2,3], [3,2], [1,4]])

print (A==B).all()
print np.array_equal(A, B)
print np.array_equiv(A, B)
print np.allclose(A, B)
Run Code Online (Sandbox Code Playgroud)

但他们只是说"假",但我仍然可以添加这两个数组.我必须检查是否允许加法/乘法(维度?),如果没有,我必须发出错误.

alb*_*ert 6

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)
Run Code Online (Sandbox Code Playgroud)

numpy引发的ValueError如下所示:

ValueError:操作数无法与形状(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)     
Run Code Online (Sandbox Code Playgroud)