列表列表的排列

时间:2014-07-06 09:11:58

标签: python combinations permutation pseudocode

假设有一个元素列表列表。每个列表中可以包含任何元素。例如[[1,2,3,4],[2,3],[4,5,6,7],[1]]。我试图生成这样的列表的排列,我应该在一个这样的排列中从最里面的列表中只选择一个。所以输出将是[1,2,4,1],[1,3,4,1] ......

示例输入= [[1,2],[3],[4]]
样本输出= [[1,3,4],[2,3,4]]

我之前尝试过一些逻辑错误的代码。以下是我处于中途并陷入困境的代码。我无法接受它。我不擅长排列和组合。

我正在尝试的内容与上面描述的相同,只是以下是坐标集。 i,最里面的元素(在输入中)是坐标集。

[[[1,2],[2,4]],[[2,3],[4,2]],[[1,5]],[[3,3],[7,2],[5,6]]]
def perm(a,length):
    arr=[]
    k=0
    while (k<length):
        temp=[]
        for i in a:


a=[[[1,2],[2,4]],[[2,3],[4,2]],[[1,5]],[[3,3],[7,2],[5,6]]]
perm(a)

如需进一步说明,请与我们联系。 任何帮助表示赞赏。

修改

我想要一个不使用itertools或任何这样的python模块的解决方案。我以前应该提到它。否则它是一个有效且非常方便的解决方案。

Psuedo code回答的逻辑可以用一种方法做一个简单的答案,而不是使用python库。很抱歉很晚才添加此详细信息。

3 个答案:

答案 0 :(得分:2)

您可以使用itertools.product轻松完成此操作:

>>> from itertools import product
>>> list(product(*[[1,2],[3],[4]]))
[(1, 3, 4), (2, 3, 4)]
>>> list(product(*[[1,2,3,4],[2,3],[4,5,6,7],[1]]))
[(1, 2, 4, 1), (1, 2, 5, 1), (1, 2, 6, 1), (1, 2, 7, 1), 
 (1, 3, 4, 1), (1, 3, 5, 1), (1, 3, 6, 1), (1, 3, 7, 1), 
 (2, 2, 4, 1), (2, 2, 5, 1), (2, 2, 6, 1), (2, 2, 7, 1), 
 (2, 3, 4, 1), (2, 3, 5, 1), (2, 3, 6, 1), (2, 3, 7, 1), 
 (3, 2, 4, 1), (3, 2, 5, 1), (3, 2, 6, 1), (3, 2, 7, 1), 
 (3, 3, 4, 1), (3, 3, 5, 1), (3, 3, 6, 1), (3, 3, 7, 1), 
 (4, 2, 4, 1), (4, 2, 5, 1), (4, 2, 6, 1), (4, 2, 7, 1), 
 (4, 3, 4, 1), (4, 3, 5, 1), (4, 3, 6, 1), (4, 3, 7, 1)]

根据文档,几乎没有任何import的实现:

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

答案 1 :(得分:1)

我发现以下递归版本比使用列表推导的版本更具可读性,但我想这是一个品味问题:

def cartesianProduct( *lists ) :
    if not lists : # nothing to do, yield empty tuple
        yield ()
    else : # let's do A x cartesianProduct( B x C x ... )
        for a in lists[0] : # each element of A
            for tup in cartesianProduct( *lists[1:] ) : # each tuple of ( B x C x ... )
                yield ( a, ) + tup # concatenate and yield 

list( product( 'AB', range(3), 'xy' ) ) == list( cartesianProduct('AB', range(3), 'xy') )

True 

答案 2 :(得分:0)

您可以使用numpy排列列表!通过这段代码:numpy.permutation(arr)所以如果你想为嵌套列表做这件事,你可以用for这样的循环来做!

相关问题