使用 numpy 获得 n 维泛化的乘法 table

Get multiplication table generalized for n dimensions with numpy

a = np.arange(1, 4).

为了得到 a 的二维乘法 table,我这样做:

>>> a * a[:, None]      
>>> array([[1, 2, 3],
           [2, 4, 6],
           [3, 6, 9]])

对于 3 个维度,我可以执行以下操作:

>>> a * a[:, None] * a[:, None, None] 
>>> array([[[ 1,  2,  3],
            [ 2,  4,  6],
            [ 3,  6,  9]],

           [[ 2,  4,  6],
            [ 4,  8, 12],
            [ 6, 12, 18]],

           [[ 3,  6,  9],
            [ 6, 12, 18],
            [ 9, 18, 27]]])

我如何编写一个函数,将一个 numpy 数组 a 和多个维度 n 作为输入并输出 n 维度乘法 table a?

这应该可以满足您的需求:

import itertools
a = np.arange(1, 4)
n = 3

def f(x, y):
    return np.expand_dims(x, len(x.shape))*y

l = list(itertools.accumulate(np.repeat(np.atleast_2d(a), n, axis=0), f))[-1]

只需将 n 更改为您需要的任何尺寸

首先,我们可以使用 numpy.expand_dims() 在 list/generator 理解中根据需要动态地 提升 数组维度,然后使用可迭代的产品工具,例如 math.prod Python 3.8+。实施将如下所示:

from math import prod

def n_dim_multiplication(arr, num_dims):
    gen_arr = (np.expand_dims(a, axis=tuple(range(1, idx+1))) for idx in range(num_dims))
    return prod(gen_arr)

3 维情况的示例 运行:

# input array
In [83]: a = np.arange(1, 4)

# desired number of dimensions
In [84]: num_dims = 3

In [85]: n_dim_multiplication(a, num_dims)
Out[85]: 
array([[[ 1,  2,  3],
        [ 2,  4,  6],
        [ 3,  6,  9]],

       [[ 2,  4,  6],
        [ 4,  8, 12],
        [ 6, 12, 18]],

       [[ 3,  6,  9],
        [ 6, 12, 18],
        [ 9, 18, 27]]])