简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM