0

I have values for a 2-dimensional list:

# 4 x 4, 2-dimensional list
values = [[4, 7, 8], 
          [1, 3, 4], 
          [7, 5, 6], 
          [2, 9, 1]]

I want to create tuples containing all possible permutations of these values (Cartesian product) for each list.

# example for the list at index 0 of values
args0 = [(4, 7, 8), (7, 4, 8), (4, 8, 7), (8, 4, 7), (7, 8, 4), (8, 7, 4)] 

Is there an easy way to go about this? I have tried itertools but cannot get it to work with "specific values".

1 Answer 1

5

What you want is the permutations of each element in the list, so just map itertools.permutations:

import itertools

values = [[4, 7, 8], 
          [1, 3, 4], 
          [7, 5, 6], 
          [2, 9, 1]]

perms = map(itertools.permutations, values)
for v in perms:
    print(list(v)) 

Result:

[(4, 7, 8), (4, 8, 7), (7, 4, 8), (7, 8, 4), (8, 4, 7), (8, 7, 4)]
[(1, 3, 4), (1, 4, 3), (3, 1, 4), (3, 4, 1), (4, 1, 3), (4, 3, 1)]
[(7, 5, 6), (7, 6, 5), (5, 7, 6), (5, 6, 7), (6, 7, 5), (6, 5, 7)]
[(2, 9, 1), (2, 1, 9), (9, 2, 1), (9, 1, 2), (1, 2, 9), (1, 9, 2)]

Here you have a live example

Sign up to request clarification or add additional context in comments.

1 Comment

that's clean :)

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.