如果您可以使用numpy并且任何为 0 的项目都可以接受 inf 的值,那么:
import numpy as np
a = np.array([[70,52,13,67],[90,48,57,26],[43,45,67,89],[88,65,44,0]],
dtype = np.float32)
>>>
>>> 1/a
array([[ 0.01428571, 0.01923077, 0.07692308, 0.01492537],
[ 0.01111111, 0.02083333, 0.01754386, 0.03846154],
[ 0.02325581, 0.02222222, 0.01492537, 0.01123596],
[ 0.01136364, 0.01538462, 0.02272727, inf]], dtype=float32)
>>> a**-1
array([[ 0.01428571, 0.01923077, 0.07692308, 0.01492537],
[ 0.01111111, 0.02083333, 0.01754386, 0.03846154],
[ 0.02325581, 0.02222222, 0.01492537, 0.01123596],
[ 0.01136364, 0.01538462, 0.02272727, inf]], dtype=float32)
>>> pow(a, -1)
array([[ 0.01428571, 0.01923077, 0.07692308, 0.01492537],
[ 0.01111111, 0.02083333, 0.01754386, 0.03846154],
[ 0.02325581, 0.02222222, 0.01492537, 0.01123596],
[ 0.01136364, 0.01538462, 0.02272727, inf]], dtype=float32)
>>>
>>> inverse_of_a = 1/a
>>> inverse_of_a
array([[ 0.01428571, 0.01923077, 0.07692308, 0.01492537],
[ 0.01111111, 0.02083333, 0.01754386, 0.03846154],
[ 0.02325581, 0.02222222, 0.01492537, 0.01123596],
[ 0.01136364, 0.01538462, 0.02272727, inf]], dtype=float32)
>>>