python - 使用 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
?
解决方案
这应该做你需要的:
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
为您需要的任何尺寸
推荐阅读
- javascript - 未捕获的类型错误:无法读取 null 的属性“地图”
- javascript - 如何从对象数组中创建数量最多的项目的对象映射?
- c# - json文件修改时如何实时更改listview值
- python-3.x - Python 线程脚本获取无效状态
- python - 如何使用 python strptime 和 strftime 将日期时间格式如 2017-02-09T09:43:04.216+1000 转换为 09-Feb-2017?
- kubernetes - openshift 3.11 安装失败 - 无法更新 cni 配置:在 /etc/cni/net.d 中找不到网络”,
- mongodb - 您只能使用弹簧数据获取井中集合的某些属性吗?
- python - 如何在numpy中使用order ='F'更改数组条目
- c - 压缩整数列表以进行搜索访问
- ios - iOS 13.0 - 支持深色模式并支持 iOS 11 和 12 的最佳方法