用于字谜的Python列表操作

时间:2017-02-15 13:06:21

标签: python list

我有一个列表,其中包含几个列表,其中包含来自给定句子的大量单词(anagrams)。

anagrams_list = [['artist', 'strait', 'traits'], ['are', 'ear', 'era'], ['detail', 'dilate', 'tailed']]

我想创建一个列表,其中包含我可以使用这些单词创建的每个句子。

这将是:

result = ['artist are detail', 'artist are dilate', 'artist are tailed', 'artist ear detail', ...]

我尝试了很多,但取决于我在anagrams_list中有多少列表,这是不可能的,我猜递归会很好,但我不知道如何创建它。

2 个答案:

答案 0 :(得分:5)

您可以使用itertools.product并通过将元组加入句子来进行后期处理:

import itertools

result = [' '.join(x) for x in itertools.product(*anagrams_list)]

这会创建:

>>> 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']

答案 1 :(得分:2)

与Willem的答案相同的主题变体是使用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))

<强>输出

'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'

该语法适用于Python 3,其中map返回迭代器。在Python 2中它返回一个列表,因此你可以摆脱list调用:

result = map(' '.join, product(*anagrams_list))

或者在Python 3的现代版本中:

result = [*map(' '.join, product(*anagrams_list))]

如果你正在使用Python 3并且实际上不需要列表,那么只需迭代地图并处理生成的每个短语:< / p>

for s in map(' '.join, product(*anagrams_list)):
    print(repr(s))