How to generate a unique list of 3 character prefixes

Viewed 57

How to make the top list to the below output in python 3:

['abc', 'def', 'ghi']


['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']

If possible, can this be solved using a for loop?

2 Answers

You are looking for itertools.product:

from itertools import product

lst = ['abc', 'def', 'ghi']

print( [''.join(c) for c in product(*lst)] )

Prints:

['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']

What you want is the product of each list values[0] * values[1] * values[2]

from itertools import product
values = ['abc', 'def', 'ghi']
result = list(map("".join, product(*values)))

CODE DEMO

Related