获取唯一列的组合

问题描述:

我想知道是否有人知道一个python函数,它返回的是不重复的列组合。例如获取唯一列的组合

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手动安装的地方。

谢谢:)

+0

好像你只需要一种组合。为此,您可以生成随机索引并将其拉出。例如'a [0] [random(2)],a [1] [random(2)]' –

+1

什么是输入? – Haranadh

+0

我的实际输入是一个方形矩阵mat = [[1,2,3],[4,5,6],[7,8,9]]。 – pyCharmer

您可以使用itertools.product和使用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) 
+0

您的代码适用于我的示例,但是当我将示例中的输入更改为方形矩阵时,它会失败。例如a = [[1,2,3],[4,5,6],[7,8,9]]不能扩展它。 – pyCharmer

+0

@pyCharmer更新了我的回答 –

+0

该死的,那里有一些漂亮的代码。需要解决这个问题,这样我才能理解。 – pyCharmer

对于较大的正方形矩阵,可以使用colu排列MNS:

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选择,第二,等等。因此,满足您的要求的每种组合都被置换为一个排列组合。 map(enumerate, permutations(range(ncols)))给出了所有有效索引的列表。对于给定索引inds,[mat[i][j] for i, j in inds]给出与该索引对应的列表。

+0

为什么丑陋'从itertools导入*'虽然? –

+0

不确定为什么它很丑,但是的确如此,你只需要'排列'。 –

+0

我收到来自行的良率的语法错误。我不这样说。你也可以用简单的方式解释这条线。 – pyCharmer