Wizard
Wizard

Reputation: 1663

Creating specific permutations Python

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".

Upvotes: 0

Views: 56

Answers (1)

Netwave
Netwave

Reputation: 42688

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

Upvotes: 5

Related Questions