【发布时间】:2019-01-29 03:34:24
【问题描述】:
我有一个句子模板字符串和一个所需替换词的字典:
template = "Who was <Name>'s <Job> in <Month>?"
dictionary = {Name: [John,Peter,Paul],
Job: [Designer,Carpenter,Lawyer],
Month:[October,July,March]
}
我想生成一个句子列表,每个替换组合一个:
question_list=["Who was <John>'s <Lawyer> in <October>?",
"Who was <Peter>'s <Lawyer> in <October>?",
"Who was <John>'s <Designer> in <July>?",
... ]
列表的顺序无所谓,不需要去掉括号''。
目前我有:
def replace(template, dictionary):
question_list = []
for word in template:
for key in dictionary:
if word == key:
new_string = template.replace(word, dictionary[key])
question_list.append(new_string)
return question_list
这会将question_list 作为一个空列表返回。
我很确定我的主要问题是我不知道如何/没有第三个for loop 来访问字典值列表中的每个项目,但我没有足够的经验知道有多糟糕我搞砸了。我该如何解决这个问题?
【问题讨论】:
-
阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 了解如何调试代码的一些技巧。
-
“单词”永远不会匹配,因为包含尖括号,因此没有任何内容附加到列表中
-
你也应该看看python给你的string operations。这些可以帮助您编写更少的代码。
-
你能改变你的字符串吗?
标签: python list dictionary replace string-matching