生成两个列表的所有可能组合的一个热矩阵?

Generating one hot matrices of all possible combinations of two lists?

假设我有一个矩阵(数组),其中元素在集合 {0,1} 中,但要遵守所有行和列的总和为 1 的约束。

matches = np.array([[0,0,1],
                    [1,0,0],
                    [0,1,0]])

有没有办法生成满足上述约束的所有可能的此类矩阵?

这是从模糊相关的 question/answer

中汲取灵感的幼稚尝试
import itertools

a = ['A','B','C']
b = ['X','Y','Z']

def get_permutations(a,b):
  index_map = {val:idx for idx,val in enumerate(a)}
  index_map.update({val:idx for idx,val in enumerate(b)})
  
  perms = [list(zip(x,b)) for x in itertools.permutations(a,len(b))]
  possible = []
  for p in perms: 
    temp_arr = np.zeros([len(a),len(b)])    
    for tup in p:
      x,y = index_map[tup[0]], index_map[tup[1]]
      temp_arr[x,y] = 1
    possible.append(temp_arr)
  return possible 


get_permutations(a,b) 

>>>
[array([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]]), array([[1., 0., 0.],
        [0., 0., 1.],
        [0., 1., 0.]]), array([[0., 1., 0.],
        [1., 0., 0.],
        [0., 0., 1.]]), array([[0., 0., 1.],
        [1., 0., 0.],
        [0., 1., 0.]]), array([[0., 1., 0.],
        [0., 0., 1.],
        [1., 0., 0.]]), array([[0., 0., 1.],
        [0., 1., 0.],
        [1., 0., 0.]])]

我的问题是:是否有更简洁或更快的方法来 return 满足上述约束的数组列表?

你的解决方法好像挺快的,能改正的地方不多。 这是我想出的

import itertools
import numpy as np

a = ['A','B','C']
b = ['X','Y','Z']

def get_permutations(a,b):
    n = len(a)
    possible = []
    for perm in itertools.permutations(range(n), n):
        matrix = np.zeros([n, n])
        i = 0
        for j in perm:
            matrix[i, j] = 1
            i += 1
        possible.append(matrix)
    return possible

get_permutations(a,b)

你的回答平均需要 3.17784857749939e-05 秒,而我的回答平均需要 9.6732497215271e-06 秒(10000 个测试样本)。差异真的很小,但如果你真的需要最快的解决方案,请考虑这个。

真正最慢的部分是 itertools.permuatations(),但我还没有找到速度相当快的替代品。