首页 > 解决方案 > 使用 numpy 获取 n 维的泛化乘法表

问题描述

a = np.arange(1, 4).

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

>>> 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维度乘法表a

标签: pythonnumpymultidimensional-arraynumpy-ndarrayarray-broadcasting

解决方案


这应该做你需要的:

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为您需要的任何尺寸


推荐阅读