获取唯一列的组合

Getting Combinations of Unique Column

我想知道是否有人知道 python 函数 returns 无重复的列组合。例如

a= [[1,2],
    [3,4]] 
# 1,4 is allowed since not the same column.
# 2,3 is allowed since not the same column.
# 1,3  is not allowed since its the same column.
# 2,4 is not allowed since its the same column.

即使它是您制作的自定义函数,我也希望看到它并了解其背后的逻辑。

此外,如果可能的话,我希望默认情况下 python 中的模块中的功能很容易获得,所以不想要像 numpy 这样的东西,我必须通过 pip 手动安装它。

谢谢:)

您可以使用 itertools.product and exclude items in the same column after generating column indices using enumerate:

from itertools import product 

def prod(*args):
   for (i, x), (j, y) in product(*map(enumerate, args)):
      if i != j:
         yield (x, y)

a= [[1,2],
    [3,4]] 
print(list(prod(*a)))
# [(1, 4), (2, 3)]

a= [[1,2,3],
    [4,5,6]]
print(list(prod(*a)))
# [(1, 5), (1, 6), (2, 4), (2, 6), (3, 4), (3, 5)]

您可以通过检查每个组合中的列是否重复来将其概括为多行和多列:

from itertools import product 

def prod(*args):
   for items in product(*map(enumerate, args)):
      if len({i for i, _ in items}) == len(items):
         yield tuple(x for _, x in items)

对于较大的方阵,您可以使用列的排列:

from itertools import *

b = [
        [1,2,3],
        [4,5,6],
        [7,8,9],
    ]


def combs(mat=b):
    ncols = len(b[0])
    yield from ([mat[i][j] for i, j in inds]
            for inds in map(enumerate,
                permutations(range(ncols))))

# In [86]: list(q.combs()) 
# Out[86]: [[1, 5, 9], [1, 6, 8], [2, 4, 9], [2, 6, 7], [3, 4, 8], [3, 5, 7]]

关于最后一行:给定一个 N x N 矩阵,有 N! 种方法可以从每一行中选取一个元素,而无需从任何列中选取两个或更多元素:你有 N 第一行的选择,第二行的 N-1 等。因此,满足您要求的每个组合都由排列确定。 map(enumerate, permutations(range(ncols))) 给出了所有有效索引的列表。对于给定的索引 inds[mat[i][j] for i, j in inds] 给出了对应于该索引的列表。