繁体   English   中英

列表列表的排列

[英]Permutations of list of lists

假设有一个元素列表列表。 每个列表中可以包含任何元素。 例如[[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代码用于回答的逻辑或用方法而不是使用python库的简单答案。 很抱歉很晚才添加这个细节。

您可以使用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)

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

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 

你可以使用numpy来排列列表! 这段代码: numpy.permutation(arr)所以如果你想为嵌套列表做到这一点,你可以用一个循环做到这一点,如for

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM