简体   繁体   English

python 中两个列表的排列而不使用 python 中的 itertools 组合或合并列表可能吗?

[英]permutations of two lists in python without combining or merging the lists using itertools in python possible?

In the case of two sublists在两个子列表的情况下

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

I would like to have the output我想要 output

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

In the case of three sublists在三个子列表的情况下

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

I would like to have the output我想要 output

`[[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]]`

Using itertools is the right way of doing this (it's part of the standard library so why not?).使用itertools是这样做的正确方法(它是标准库的一部分,为什么不呢?)。 For example:例如:

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)]

However, it is of course possible to implement a permutation function and a product function :但是,当然可以实现一个排列 function一个产品 function

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

Which we can then use to achieve the same goal:然后我们可以使用它来实现相同的目标:

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

But this will be slower, prone to bugs and it means more code to maintain.但这会更慢,容易出现错误,这意味着需要维护更多的代码。 The only interesting thing here I think is to implement it yourself and see what you end up with, then simply use itertools .我认为这里唯一有趣的事情是自己实现它并查看最终结果,然后简单地使用itertools

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

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