簡體   English   中英

For循環枚舉。 蟒蛇

[英]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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM