1

In the case of two sublists

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

I would like to have the 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

`[[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]]`
Ivo Reints
  • 11
  • 1

1 Answers1

1

Using itertools is the right way of doing this (it's part of the standard library so why not?). 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:

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.

cglacet
  • 8,873
  • 4
  • 45
  • 60