Reputation: 23
I don't know the type of this algmaybe it's famous..
I have a liste of this form
L = [ ["a"] , ["b"] , ["c"] ] , [ ["d"] , ["e"] , ["f"] ] , ["g"], ["h"], ["i"] ] ,[ ["j"] , ["k"] , ["l"] ]
where the letter are words and the length of L could be from 2 to 50 elements but inside the list are always 3 elements long.
And I want to create a list who build all this string :
"adgj"
"adgk"
"adgl"
"adhj"
"adhk"
"adhl"
"adij"
"adik"
"adil"
"aegj"
ect all the way to "cfil"
could someone tell me what to do or where to look for?
Thank's a lot for your help..
Upvotes: 2
Views: 82
Reputation: 11060
You can use itertools.product
to achieve this efficiently:
import itertools
L = [['a'], ['b'], ['c']], [['d'], ['e'], ['f']], [['g'], ['h'], ['i']], [['j'], ['k'], ['l']]
for item in itertools.product(*L):
''.join([str(x) for y in item for x in y])
Upvotes: 5
Reputation: 656
If you don't want to use any other module and do all the work yourself, following code will give you the result,
L = [[ ["a"] , ["b"] , ["c"] ] , [ ["d"] , ["e"] , ["f"] ] , [["g"], ["h"], ["i"] ] ,[ ["j"] , ["k"] , ["l"] ]]
words = []
def a(string):
i = len(string)
if(i==len(L)):
words.append(string)
else:
for element in L[i]:
a(string+element[0])
a('')
Upvotes: 2