有多种方法可以解决这个问题。正如评论中所提到的,你要做的是让每一个组合都装满9个空桶中的3个。然后将这些存储桶表示为一个矩阵,然后就只需要改变存储桶的存储方式。你可以很容易地创建矩阵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]
下面是一个随机输出示例:
^{pr2}$