In addition to what @JoshAdel has suggested, you can also use the outer
method of any numpy ufunc
to do the broadcasting in the case of two arrays.
In this case, you just want np.subtract.outer(A, B)
(Or, rather, the absolute value of it).
While either one is fairly readable for this example, in some cases broadcasting is more useful, while in others using ufunc methods is cleaner.
Either way, it's useful to know both tricks.
E.g.
import numpy as np
A = np.array([1,3,6])
B = np.array([2,4,6])
diff = np.subtract.outer(A, B)
result = np.abs(diff)
Basically, you can use outer
, accumulate
, reduce
, and reduceat
with any numpy ufunc
such as subtract
, multiply
, divide
, or even things like logical_and
, etc.
For example, np.cumsum
is equivalent to np.add.accumulate
. This means you could implement something like a cumdiv
by np.divide.accumulate
if you even needed to.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…