python - 询问用户列表的索引,Python

标签 python list search dictionary indexing

这些词典快要死我了!

这是我的 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/

相关文章:

javascript - 如果取消选中所有子复选框,如何取消选中父复选框,反之亦然?

list - grails如何检查值是否在gsp的列表中

regex - 如何使用正则表达式在 Visual Studio Code 中搜索以仅匹配未注释的代码?

python2.7.8 : TypeError: expected string or buffer with bs4 and re

python - 属性错误: 'list' object has no attribute 'lower' gensim

python - 如何使用 pip 更新 Python 标准库包?

Python 查询对象不可序列化

python - 一次性计算精度、召回率和 F 分数 - python

php - 如何在我的站点中创建全局搜索

powershell - Powershell代码片段的哪一部分使运行时间很长?