Generate wordlist by List of List of character

316 views Asked by At

I want to generate a wordlist by list of list of character, like:

A=[['a','b','c'],['d'],['e','f']]

where a[0] stores all possible character at first place, a[1] stores all possible character at second place and so on. All possible words generated by list 'A' will be:

ade
adf
bde
bdf
cde
cdf

I am generating this list by:

for i in a[0]:
    for j in a[1]:
        for k in a[2]:
            print i+j+k

This code works fine for fixed length of list(i.e. len(A)). I want to write a generalize code which can generate wordlist by list of any size.

1

There are 1 answers

1
Anshul Goyal On BEST ANSWER

You can do this with itertools.product:

>>> from itertools import product
>>> characters = [['a','b','c'],['d'],['e','f']]
>>> [''.join(item) for item in product(*characters)]
['ade', 'adf', 'bde', 'bdf', 'cde', 'cdf']

This will work irrespective of the lengths of the sublists, as the product method computes a Cartesian product of the elements of sublist. Also, since we are passing the sublists with python *characters magic, we can pass any number of sublist.