2015-05-20 35 views
2

這些字典正在殺死我!詢問用戶索引的列表,Python

這是我的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" 
} 
] 

我想讓用戶搜索一個索引,然後列出該索引的值(如果有的話)。目前,我提示用戶輸入,然後查找問題索引,然後檢查輸入是否等於索引,現在即使輸入了正確的索引,它也會返回False,False。我在正確的軌道上,但語義錯誤?或者我應該研究另一條路線?

import json 


f = open('question.txt', 'r') 
questions = json.load(f) 
f.close() 

value = inputSomething('Enter Index number: ') 

for i in questions: 
    if value == i: 
     print("True") 

    else: 
     print("False") 

回答

1

您正在遍歷列表值。 for i in questions 將迭代列表值而不是列表索引,

您需要迭代列表的索引。爲此你可以使用枚舉。你應該試試這種方式..

for index, question_dict in enumerate(questions): 
    if index == int(value): 
     print("True") 

    else: 
     print("False") 
+0

我得到一個NameError,我沒有定義? –

+0

看到我更新的答案.. – Zealous

+0

我仍然收到假,假。請注意我正在嘗試從字典中的值中獲取每個字典的索引號(在列表中)。 –

1

在Python中最好是not check beforehand, but try and deal with error if it occurs

這是遵循這種做法的解決方案。花點時間仔細看看這裏的邏輯,它可能會幫助你在將來:

import json 
import sys 

    # BTW: this is the 'pythonic' way of reading from file: 
# with open('question.txt') as f: 
#  questions = json.load(f) 


questions = [ 
    { 
     "question": "Example Question 1? ", 
     "answer": "Correct answer", 
    }, 
    { 
     "question": "How many good Matrix movies are there? ", 
     "answer": "1", 
    } 
] 


try: 
    value = int(input('Enter Index number: ')) # can raise ValueError 
    question_item = questions[value] # can raise IndexError 
except (ValueError, IndexError) as err: 
    print('This question does not exist!') 
    sys.exit(err) 

# print(question_item) 

answer = input(question_item['question']) 

# let's strip whitespace from ends of string and change to lowercase: 
answer = answer.strip().lower() 

if answer == question_item['answer'].strip().lower(): 
    print('Good job!') 
else: 
    print('Wrong answer. Better luck next time!') 
+0

這真的很有幫助。謝謝。 –