这些词典快要死我了!
这是我的 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")
最佳答案
您正在迭代列表值。 对于问题中的 i
将迭代列表值而不是列表索引,
您需要迭代列表的索引。为此,您可以使用枚举。你应该尝试这种方式..
for index, question_dict in enumerate(questions):
if index == int(value):
print("True")
else:
print("False")
关于python - 询问用户列表的索引,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30350464/