我想创建一个创建3x3矩阵的python脚本
并且填充它的所有可能性,一次填充3个方块,如附图所示。
答案 0 :(得分:3)
有多种方法可以解决这个问题。正如评论中所提到的,你要做的就是让每个组合填充9个空桶中的3个。之后将这些桶表示为矩阵只是改变存储桶的存储方式。你是对的,numpy会让你轻松创建矩阵
from itertools import permutations
import numpy as np
# Gets all possible combinations of non-zero indices
non_zero_index_sets = permutations(range(9), 3)
# Turn these sets of 3 non-zero indices into length 9 vectors just containing
# zeros and ones, e.g. [2, 7, 8] becomes [0, 0, 1, 0, 0, 0, 0, 1, 1]
vectors = []
for non_zero_set in non_zero_index_sets:
vector = np.zeros(9)
vector[list(non_zero_set)] = 1
vectors.append(vector)
# Turn each length-nine vector into a 3x3 matrix, e.g.
# [0, 0, 1, 0, 0, 0, 0, 1, 1] becomes [[0, 0, 1], [0, 0, 0], [0, 1, 1]]
matrices = [vector.reshape((3, 3)) for vector in vectors]
这是一个随机输出示例:
ipdb> matrices[50]
array([[ 1., 0., 1.],
[ 0., 0., 0.],
[ 0., 0., 1.]])
查看排列文档,了解更多详细信息。您可以将其视为从您想要非零的可能索引列表中选择3个元素。 https://docs.python.org/2/library/itertools.html#itertools.permutations