首页 > 解决方案 > python中两个列表的排列而不使用python中的itertools组合或合并列表可能吗?

问题描述

在两个子列表的情况下

`[[A,B],[1,2]]`

我想要输出

[[A,B],[1,2] [A,B],[2,1] [B,A],[1,2] [B,A],[2,1]]

在三个子列表的情况下

`[[A,B],[1,2], [c, d]]`

我想要输出

`[[A,B],[1,2], [c, d],
 [A,B],[1,2], [d, c],
 [A,B],[2,1], [c, d],
 [A,B],[2,1], [d, c],
 [B,A],[1,2], [c, d],
 [B,A],[1,2], [d, c],
 [B,A],[2,1], [c, d]
 [B,A],[2,1], [d, c]]`

标签: pythonlistpermutationitertools

解决方案


使用itertools是这样做的正确方法(它是标准库的一部分,为什么不呢?)。例如:

from itertools import permutations, product

values = [['A', 'B'], [1, 2]]
sub_permutations = ([list(p) for p in permutations(l)] for l in values)
values_perms = [list(v) for v in product(*sub_permutations)]

但是,当然可以实现置换函数乘积函数

def permutations(values):
    if not values: 
        return
    for i in range(len(values)):
        for p in all_perms(values[1:]):
            yield [*p[:i], values[0], *p[i:]]

def product(lists):
    result = [[]]
    for pool in lists:
        result = [r + [p] for r in result for p in pool]
    return result

然后我们可以使用它来实现相同的目标:

values = [['A', 'B'], [1, 2]]
values_perms = product(list(permutations(l)) for l in values)

但这会更慢,容易出现错误,这意味着需要维护更多的代码。我认为这里唯一有趣的事情是自己实现它,看看你最终会得到什么,然后简单地使用itertools.


推荐阅读