ben
ben

Reputation: 207

Permutations within and across list of lists [python]

There are many questions that are related but none that I could find to do exactly what I am looking for. Essentially, I want to get all permutations of each sub-list put together for all possible combinations but keeping them separate. As such:

input=[[1,2,3],[4],[5,6]]

desired output:

[[1,2,3],[4],[6,5]]

[[2,1,3],[4],[5,6]]

[[2,1,3],[4],[5,6]]

[[3,1,2],[4],[5,6]]

etc...

I believe the following code will work, but I was wondering if there were any more efficient or succinct strategies. Thank you very much.

input=[[1,2,3],[4],[5,6]]
all_lists=[]

for i in xrange(len(input)):
    all_lists.append(list(itertools.permutations(input[i])))

all_combinations = list(itertools.product(*all_lists))

## concat them together
combinations_combined = [list(itertools.chain(*a)) for a in all_combinations]

Upvotes: 2

Views: 369

Answers (2)

user9440895
user9440895

Reputation:

And_the_case [[3, 1, 2], [4], [5, 6, [7,8[9,10,11]]? If it's nested list?

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

We can first use list comprehension to generate all permutations for each sublist:

perms = [list(map(list,permutations(subl))) for subl in data]

and then we can use product to obtain products.

for data in product(*perms):
    print(list(data))

Or in full:

from itertools import permutations, product

def product_perms(data):
    perms = [list(map(list,permutations(subl))) for subl in data]
    for data in product(*perms):
        print(list(data))

This produces:

>>> product_perms(data)
[[1, 2, 3], [4], [5, 6]]
[[1, 2, 3], [4], [6, 5]]
[[1, 3, 2], [4], [5, 6]]
[[1, 3, 2], [4], [6, 5]]
[[2, 1, 3], [4], [5, 6]]
[[2, 1, 3], [4], [6, 5]]
[[2, 3, 1], [4], [5, 6]]
[[2, 3, 1], [4], [6, 5]]
[[3, 1, 2], [4], [5, 6]]
[[3, 1, 2], [4], [6, 5]]
[[3, 2, 1], [4], [5, 6]]
[[3, 2, 1], [4], [6, 5]]

In case you want to return such a list, you can use:

def product_perms(data):
    perms = [list(map(list,permutations(subl))) for subl in data]
    return [list(data) for data in product(*perms)]

Upvotes: 2

Related Questions