首页 > 解决方案 > 在 Python 中使用网格搜索创建维度为 n * 3 的矩阵

问题描述

我想要一个像下面这样的矩阵,3列,n行。每行总和为一。

[[0, 0, 1], [0, 0.1, 0.9], [0.1, 0.1, 0.8], [0.1, 0.2, 0.7] ...]

有这样做的图书馆吗?

标签: pythonmatrixgrid-search

解决方案


您可以使用itertools.combinations_with_replacement从 0.0 到 1.0 之间的 11 个插槽中选择 2 个分区:

from itertools import combinations_with_replacement
[[n / 10 for n in (a, b - a, 10 - b)] for a, b in combinations_with_replacement(range(11), 2)]

这将返回:

[[0.0, 0.0, 1.0],
 [0.0, 0.1, 0.9],
 [0.0, 0.2, 0.8],
 [0.0, 0.3, 0.7],
 [0.0, 0.4, 0.6],
 [0.0, 0.5, 0.5],
 [0.0, 0.6, 0.4],
 [0.0, 0.7, 0.3],
 [0.0, 0.8, 0.2],
 [0.0, 0.9, 0.1],
 [0.0, 1.0, 0.0],
 [0.1, 0.0, 0.9],
 [0.1, 0.1, 0.8],
 [0.1, 0.2, 0.7],
 [0.1, 0.3, 0.6],
 [0.1, 0.4, 0.5],
 [0.1, 0.5, 0.4],
 [0.1, 0.6, 0.3],
 [0.1, 0.7, 0.2],
 [0.1, 0.8, 0.1],
 [0.1, 0.9, 0.0],
 [0.2, 0.0, 0.8],
 [0.2, 0.1, 0.7],
 [0.2, 0.2, 0.6],
 [0.2, 0.3, 0.5],
 [0.2, 0.4, 0.4],
 [0.2, 0.5, 0.3],
 [0.2, 0.6, 0.2],
 [0.2, 0.7, 0.1],
 [0.2, 0.8, 0.0],
 [0.3, 0.0, 0.7],
 [0.3, 0.1, 0.6],
 [0.3, 0.2, 0.5],
 [0.3, 0.3, 0.4],
 [0.3, 0.4, 0.3],
 [0.3, 0.5, 0.2],
 [0.3, 0.6, 0.1],
 [0.3, 0.7, 0.0],
 [0.4, 0.0, 0.6],
 [0.4, 0.1, 0.5],
 [0.4, 0.2, 0.4],
 [0.4, 0.3, 0.3],
 [0.4, 0.4, 0.2],
 [0.4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