现在我有一个包含两个词典的列表的JSON。此代码允许用户通过索引号搜索列表,检索字典。目前我得到两个打印结果,每个字典一个,例如,如果我输入索引号1,我得到:没有索引号,然后打印出一个字典。而不是这个我想只得到一个结果打印找到的字典或1错误。我不应该使用枚举吗?
这是我的JSON(问题),其中包含2个dicts列表。
[{
"wrong3": "Nope, also wrong",
"question": "Example Question 1",
"wrong1": "Incorrect answer",
"wrong2": "Another wrong one",
"answer": "Correct answer"
}, {
"wrong3": "0",
"question": "How many good Matrix movies are there?",
"wrong1": "2",
"wrong2": "3",
"answer": "1"
}]
这是我的代码
f = open('question.txt', 'r')
questions = json.load(f)
f.close()
value = inputSomething('Enter Index number: ')
for index, question_dict in enumerate(questions):
if index == int(value):
print(index, ') ', question_dict['question'],
'\nCorrect:', question_dict['answer'],
'\nIncorrect:', question_dict['wrong1'],
'\nIncorrect:', question_dict['wrong2'],
'\nIncorrect:', question_dict['wrong3'])
break
if not index == int(value):
print('No index exists')
答案 0 :(得分:1)
恕我直言,我认为你不需要使用enumerate
。
我个人认为你不应该绕过questions
。
为什么不这样做:
# assuming the user enters integers from 1 to N.
user_index = int(value) - 1
if -1 < user_index < len(questions):
# print the question
else:
print('No index exists')
虽然我们在其中,但为什么不使用with
关键字:
with open('question.txt', 'r') as f:
questions = json.load(f)
而不是close
:
f = open('question.txt', 'r')
questions = json.load(f)
f.close()
答案 1 :(得分:0)
# Use `with` to make sure the file is closed properly
with open('question.txt', 'r') as f:
questions = json.load(f)
value = inputSomething('Enter Index number: ')
queried_index = int(value)
# Since `questions` is a list, why don't you just *index` it with the input value
if 0 <= queried_index < len(questions):
question_dict = questions[queried_index]
# Let `print` take care of the `\n` for you
print(index, ') ', question_dict['question'])
print('Correct:', question_dict['answer'])
print('Incorrect:', question_dict['wrong1'])
print('Incorrect:', question_dict['wrong2'])
print('Incorrect:', question_dict['wrong3'])
else:
print('No index exists')