Thromobocytin
Thromobocytin

Reputation: 33

How to get every string variations with list of possibilities for each position

Let's say I have a list of lists called master_list, which has the following properties:

  1. Each list inside the master_list contains strings that are single digit positive integers
  2. Each list inside the master_list has a length from 2 to 5
  3. The master_list has a length from 1 to 8

What I want to do is return a list of string variations using the list of posibilities for each position.

Here is an example of a master_list and what the output would look like:

master_list = [['3', '2', '6'], ['6', '5', '3', '9'], ['9', '8', '6']]

#  In this case the output would contain 3*4*3 = 36 elements 

output = ["339","366","399","658","636","258","268","669","668","266","369","398",
           "256","296","259","368","638","396","238","356","659","639","666","359",
           "336","299","338","696","269","358","656","698","699","298","236","239"]

Upvotes: 2

Views: 130

Answers (2)

abhiarora
abhiarora

Reputation: 10450

've tried iterating through each list with nested for loops, then I realized that I would need to use recursion because the number of lists is variable. But I'm stuck on how to do that. The nested loops got me the output above but its essentially hard coded for that case.

Try this (It uses itertools.product):

import itertools

li = [['3', '2', '6'], ['6', '5', '3', '9'], ['9', '8', '6']]
result = [''.join(i) for i in itertools.product(*li)]
print(result)

Outputs:

['369', '368', '366', '359', '358', '356', '339', '338', '336', '399', '398', '396', '269', '268', '266', '259', '258', '256', '239', '238', '236', '299', '298', '296', '669', '668', '666', '659', '658', '656', '639', '638', '636', '699', '698', '696']

If you want to convert each element into int:

result = [int(''.join(i)) for i in itertools.product(*li)]

Upvotes: 3

trigonom
trigonom

Reputation: 528

itertools product will give you all combinations in tuples as in this example All combinations of a list of lists then you can concat each tuple to a single string, or create a number and convert to string

Upvotes: 1

Related Questions