我想在以下类型的python中使用字典
dictionary = {
"Who is Elon Musk":
"Elon Reeve Musk FRS is an American business magnate, investor and engineer. He is the founder, CEO, and lead designer of SpaceX; co-founder, CEO, and product architect of Tesla, Inc.; and co-founder and CEO of Neuralink " ,
"Second Question":
"Second answer"
}
我想通过上述方法从问题中检索答案。
这种方法有什么问题,什么是正确的方法。还有比使用字典执行上述任务更好的方法。
答案 0 :(得分:1)
您可以使用换行符"\n"
来显示应该在何处换行。连续字符串文字被解释为单个字符串,因此我们可以轻松地将文字分解为最终字符串将被破坏的位置。
dictionary = {
"Who is Elon Musk":
"Elon Reeve Musk FRS is an American business magnate, investor and engineer.\n"
"He is the founder, CEO, and lead designer of SpaceX;\n"
"co-founder, CEO, and product architect of Tesla, Inc.;\n"
"and co-founder and CEO of Neuralink." ,
"Second Question":
"Second answer"
}
用三引号引起来的字符串可以在这里工作,但是它们不能很好地配合Python的缩进规则,使代码难以阅读。
答案 1 :(得分:0)
字典通常用于可构造为键值对的数据。在这种情况下,它假定您知道确切的问题才能查找答案(这真的是个好主意吗?)。那用一套呢?它还可以防止重复。