Home > Mobile >  All permutations of random value within list of values using python
All permutations of random value within list of values using python

Time:12-05

I need to reach the following result using python (thought about itertools), I have 4 rows that each can get one the values = ['v1', 'v2', 'v3'], since we have 3 options and 4 rows, then number of possibilities will be 3^4 = 81

For example:

    col1  col2  col3 ....... col81  
1    v1    v1    v_  
2    v2    v3
3    v1    v2
4    v3    v1

how can I achieve it, in such a way that I cover all the possibilities?

CodePudding user response:

Seems like you're looking for the "product" not the "permutation". Try this:

import itertools
from pprint import pprint

v = [1, 2, 3]

pprint(list(itertools.product(v, repeat=4)))
[(1, 1, 1, 1),
 (1, 1, 1, 2),
 (1, 1, 1, 3),
 (1, 1, 2, 1),
 (1, 1, 2, 2),
...
 (3, 3, 2, 3),
 (3, 3, 3, 1),
 (3, 3, 3, 2),
 (3, 3, 3, 3)]

If you need the transpose of that, you can do this:

import itertools
from pprint import pprint

v = [1, 2, 3]

product = list(itertools.product(v, repeat=4))
transpose = list(map(list, zip(*product)))
pprint(transpose)
  • Related