2

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]
2
  • 2
    Don't name variables things like input, you override the reference to the input builtin. Commented Sep 21, 2017 at 21:23
  • i do not in my code- this was just for the example. I'll refrain from doing it here as well. Commented Sep 21, 2017 at 21:27

2 Answers 2

2

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)]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.