For 循环枚举。 Python

For loop enumerate. Python

现在我有一个 JSON,其中包含一个包含两个词典的列表。此代码允许用户通过索引号搜索列表,检索字典。目前我得到两个打印结果,每个字典一个,例如,如果我输入索引号 1,我得到:没有索引号,然后打印出一个字典。而不是这个,我只想打印一个结果,要么是找到的字典,要么是 1 个错误。我不应该使用枚举吗?

这是我的JSON(问题),其中包含 2 个字典的列表。

[{
    "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')

恕我直言,我认为您不需要使用 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()
# 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')