2015-05-26 3 views
1

Сейчас у меня есть JSON со списком, содержащим два словаря. Этот код позволяет пользователю выполнять поиск по списку по номеру индекса, извлекая словарь. В настоящее время я получаю два печатных результата по одному для каждого словаря, например, если я набрал индекс номер 1, я получаю: No Index Number, а затем распечатал один словарь. Вместо этого я хотел бы получить только один результат, напечатанный либо найденным словарем, либо 1 ошибка. Должен ли я не использовать перечисление?Для перечисления циклов. 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" 
}] 

Вот мой код

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

Быстрый note: 'continue' не может использоваться d вне петли – Zizouz212

+0

Ahhh. Я скопировал это из большей части. Изменен @ Zizouz212 –

ответ

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') 
+0

Вы скопировали эту ошибку '0 <' из другого ответа? :-P –

+0

Выход из кода schlezzz15 Я пытался выяснить, как индексироваться с помощью ввода, просто не был уверен в синтаксисе. Большое спасибо! –

+0

Я изменил 0 на -1 в моем коде. –

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

Без проблем, amigo;) Наслаждался возможностью помочь вам. –

+1

@Youngn 'Это работает? Вы пробовали индекс 0? –

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