简体   繁体   中英

Generate 2 dimensional permutations of a python list

I have a python list as follows:

[['row_0','row_0_0','row_0_1'],['row_1','row_1_0','row_1_1']]

where each list in the parent list is called a row and each item in child list is called a column . For example: ['row_0','row_0_0','row_0_1'] is a row. and 'row_0','row_0_0' and 'row_0_1' are columns of this row.

I want to generate permutations in such a way that

  1. The total number of rows remain the same as in the original parent list ie,2.

  2. The permutations of the columns of each row remain within that row. For example: ['row_0','row_0_0','row_0_1'] can have a permutation ['row_0','row_0_1','row_0_0'] , ['row_0','row_0_0','row_0_1'] .

  3. The first column of each row never changes in permutations. For example: 'row_0' in and 'row_1' always remain the first items in their list.

So far what I have implemented looks like this:

perm_list =  [['row_0','row_0_0','row_0_1'],['row_1','row_1_0','row_1_1']]
all_permutations = list(itertools.permutations(perm_list, len(perm_list))
print(all_permutations)

but this only generates permutations at the parent list level. I was wondering if python has a builtin tool to handle a functionality like this that can be tweaked to fit my needs. Any suggestions will be appreciated.

EDIT

The output I am looking for is something like this:

[
  [['row_0','row_0_0','row_0_1'],['row_1','row_1_0','row_1_1']],
  [['row_0','row_0_1','row_0_0'],['row_1','row_1_1','row_1_0']],
  [['row_1','row_1_0','row_1_1'],['row_0','row_0_0','row_0_1']],
  [['row_1','row_1_1','row_1_0'],['row_0','row_0_1','row_0_0']],
]

a. The first item in each child list remained the same. b. The items in each child list remained within that list. c. The total number of items for both parent and child list remained the same.

From what I know , there is no build-in function for what you described

l1=[[list((x[0],)+y) for y in itertools.permutations(x[1:], len(x)-1)] for x in l ]
list(map(list,itertools.product(l1[0],l1[1])))
[[['row_0', 'row_0_0', 'row_0_1'], ['row_1', 'row_1_0', 'row_1_1']], 
[['row_0', 'row_0_0', 'row_0_1'], ['row_1', 'row_1_1', 'row_1_0']], 
[['row_0', 'row_0_1', 'row_0_0'], ['row_1', 'row_1_0', 'row_1_1']], 
[['row_0', 'row_0_1', 'row_0_0'], ['row_1', 'row_1_1', 'row_1_0']]]

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