I have a list which contains several lists with a lot of words (anagrams) from a given sentence.
anagrams_list = [['artist', 'strait', 'traits'], ['are', 'ear', 'era'], ['detail', 'dilate', 'tailed']]
I want to create a list that contains each sentence that I can create with these words.
Here it will be :
result = ['artist are detail', 'artist are dilate', 'artist are tailed', 'artist ear detail', ...]
I tried with a lot of for but depends on how many list I have in anagrams_list it's just impossible, and i guess recursive would be fine but i have no idea on how to create this.
You can use itertools.product for that and do post processing by joining the tuple into a sentence:
import itertools
result = [' '.join(x) for x in itertools.product(*anagrams_list)]
this creates:
>>> result
['artist are detail', 'artist are dilate', 'artist are tailed', 'artist ear detail', 'artist ear dilate', 'artist ear tailed', 'artist era detail', 'artist era dilate', 'artist era tailed', 'strait are detail', 'strait are dilate', 'strait are tailed', 'strait ear detail', 'strait ear dilate', 'strait ear tailed', 'strait era detail', 'strait era dilate', 'strait era tailed', 'traits are detail', 'traits are dilate', 'traits are tailed', 'traits ear detail', 'traits ear dilate', 'traits ear tailed', 'traits era detail', 'traits era dilate', 'traits era tailed']
A variation on the same theme as Willem's answer is to use map:
from itertools import product
anagrams_list = [
['artist', 'strait', 'traits'],
['are', 'ear', 'era'],
['detail', 'dilate', 'tailed']
]
result = list(map(' '.join, product(*anagrams_list)))
for s in result:
print(repr(s))
output
'artist are detail'
'artist are dilate'
'artist are tailed'
'artist ear detail'
'artist ear dilate'
'artist ear tailed'
'artist era detail'
'artist era dilate'
'artist era tailed'
'strait are detail'
'strait are dilate'
'strait are tailed'
'strait ear detail'
'strait ear dilate'
'strait ear tailed'
'strait era detail'
'strait era dilate'
'strait era tailed'
'traits are detail'
'traits are dilate'
'traits are tailed'
'traits ear detail'
'traits ear dilate'
'traits ear tailed'
'traits era detail'
'traits era dilate'
'traits era tailed'
That syntax is for Python 3, where map returns an iterator. In Python 2 it returns a list, so you can get rid of the list call:
result = map(' '.join, product(*anagrams_list))
Or in modern versions of Python 3:
result = [*map(' '.join, product(*anagrams_list))]
If you're using Python 3 and you don't actually need a list, then just iterate over the map and process each phrase as it's generated:
for s in map(' '.join, product(*anagrams_list)):
print(repr(s))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With