您可以使用 Python 的itertools.product 解决该问题。这是我解决它的方法。
from itertools import product
def solution(words, syn):
new_words_list = []
for w in words:
if w in syn.keys():
new_words_list.append(syn[w] + [w])
else:
new_words_list.append([w])
answer = list(product(*new_words_list))
return answer
鉴于您的 words 以字符串列表的形式给出,syn 以字典的形式给出,其中键是 words 中的单词,值是同义词列表,请采用 @987654326 @ 和 syn 作为输入,并为每个单词生成一个名为 new_words_list 的嵌套列表。
[['feline', 'cat'], ['below', 'down', 'beneath', 'under'], ['bench', 'board', 'table']]
由于words 和syn 的长度是变量,因此使用列表推导运算的* 将嵌套列表new_words_list 传递给itertools.product()。 itertools.product() 计算给定迭代的笛卡尔积。
这段代码 sn-p 的输出如下。
['feline', 'below', 'bench']
['feline', 'below', 'board']
['feline', 'below', 'table']
['feline', 'down', 'bench']
['feline', 'down', 'board']
['feline', 'down', 'table']
['feline', 'beneath', 'bench']
['feline', 'beneath', 'board']
['feline', 'beneath', 'table']
['feline', 'under', 'bench']
['feline', 'under', 'board']
['feline', 'under', 'table']
['cat', 'below', 'bench']
['cat', 'below', 'board']
['cat', 'below', 'table']
['cat', 'down', 'bench']
['cat', 'down', 'board']
['cat', 'down', 'table']
['cat', 'beneath', 'bench']
['cat', 'beneath', 'board']
['cat', 'beneath', 'table']
['cat', 'under', 'bench']
['cat', 'under', 'board']
['cat', 'under', 'table']