python - 在python中快速替换2个矩阵
问题描述
抱歉,如果这是一个简单的问题,我是 python 新手。我有一个字符串(单词数组)和一个二维单词,我将一个一个地替换它们,如下所示:
str="Jim is a good person"
# and will convert to:
parts=['Jim','is','a','good','person']
和一个二维数组,其中每个维度是一个单词数组,可以用部分中具有相同索引的元素替换。例如这样的:
replacement=[['john','Nock','Kati'],
['were','was','are'],
['a','an'],
['bad','perfect','awesome'],
['cat','human','dog']]
结果可能是这样的:
1: nike is a good person
2: John are an bad human
3: Kati were a perfect cat
and so on
实际上,我将用一些可能的单词替换句子的每个单词,然后对新句子进行一些计算。我需要实现所有可能的替换。
非常感谢。
解决方案
itertools.product可能是创建您正在寻找的所有组合的最佳选择。
让我们以您的替换清单为起点,了解可行的方法。获得您正在寻找的所有组合的方法可能看起来像这样
from itertools import product
word_options=[['john','Nock','Kati'],
['were','was','are'],
['a','an'],
['bad','perfect','awesome'],
['cat','human','dog']]
for option in product(*word_options):
new_sentence = ' '.join(option)
#do calculation on new_sentence
被迭代的每个选项都是一个元组,其中每个元素都是来自原始二维列表的每个单独子列表的单个选择。然后' '.join(option)
将单个字符串组合成一个字符串,其中单词用空格分隔。如果您只是 print new_sentence
,输出将如下所示。
john were a bad cat
john were a bad human
john were a bad dog
john were a perfect cat
john were a perfect human
john were a perfect dog
.
.
.
Kati are an perfect cat
Kati are an perfect human
Kati are an perfect dog
Kati are an awesome cat
Kati are an awesome human
Kati are an awesome dog