2015-05-20 2 views
2

Эти словари убивают меня!Запросить индекс для индекса, Python

Вот мой 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" 
} 
] 

Я пытаюсь разрешить пользователю искать индекс, а затем перечислить значение этого индекса (если есть). В настоящее время я запрашиваю пользователя для ввода, затем нахожу указатели вопросов, а затем проверяет, равен ли вход индексу, теперь он возвращает 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

Я получаю имяError, i не определен? –

+0

см. Мой обновленный ответ. – Zealous

+0

Я все еще получаю False, False. Обратите внимание: я пытаюсь получить индексный номер каждого словаря (в списке) не из значений внутри словаря. –

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

Это действительно полезно. Благодарю. –

Смежные вопросы