json 在Python中简化嵌套if语句

rxztt3cl  于 2023-03-04  发布在  Python
关注(0)|答案(1)|浏览(121)

我正在开发一个存储多项选择题的JSON数据库。我定义了一个函数,它接受一些非强制性的参数,以便根据您的需要(难度、主题、关键字...)获取问题,因此我觉得需要使用许多if-else语句。
下面的(symbolic)代码工作正常,但是很难理解。

def getq(mine, subject, difficulty, keyword):
    with open("questions.json", "r") as f:
        data = json.load(f)

    for id in data.keys():
        if mine == True:
            if subject == True:
                if difficulty == True:
                    if keyword == True:
                        ...
                    else:
                        ...
                else:
                    if keyword == True:
                        ...
                    else:
                        ...
            else:
                if difficulty == True:
                    if keyword == True:
                        ...
                    else:
                        ...
                else:
                    if keyword == True:
                        ...
                    else:
                        ...
        elif subject == True:
            if difficulty == True:
                if keyword == True:
                    ...
                else:
                    ...
            else:
                if keyword == True:
                    ...
                else:
                    ...
        else:
            if difficulty == True:
                if keyword == True:
                    ...
                else:
                    ...
            else:
                if keyword == True:
                    ...
                else:
                    ...

它使用以下JSON结构:

{
    "1": {
        "question": "What's the capital of Spain?",
        "subject": "",
        "date" : "",
        "timesright" : 2,
        "timeswrong" : 3,
        "difficulty": "",  # This would be a function of timesright and timeswrong
        "keywords" : "geography, general knowledge",
        "explanation": "",
        "answers": [
            {
                "id": 1,
                "answer": "Paris",
                "is_correct": false
            },
            {
                "id": 2,
                "answer": "Madrid",
                "is_correct": true
            },
            {
                "id": 3,
                "answer": "Roma",
                "is_correct": false
            },
            {
                "id": 4,
                "answer": "Moscow",
                "is_correct": false
            }
        ]
    }
}

我怎样才能让它看起来更容易和/或更有效率呢?也许是麻木?我会非常感谢其他的建议。也许使用JSON不是最好的主意,因为我打算通过命令编辑它?* 我是一个新手,所以我不知道。*

ubof19bj

ubof19bj1#

正如评论中所建议的-最简单的方法是将json存储为panda Dataframe 。
请考虑以下json对象作为示例:

{
    "1": {
        "question": "some question?",
        "choices": [1,2,3,4],
        "answer": 0,
        "subject": "science",
        "difficulty": "medium",
        "mine": "foobar"
    },
    "2": {
        "question": "some question?",
        "choices": [1,2,3,4],
        "answer": 0,
        "subject": "math",
        "difficulty": "medium",
        "mine": "foobar"
    },
    "3": {
        "question": "some question?",
        "choices": [1,2,3,4],
        "answer": 0,
        "subject": "math",
        "difficulty": "medium",
        "mine": "foobar"
    }
}

假设读取为json_str,函数getq将类似于:

def getq(mine='', subject='', difficulty='', keyword=''):
    df = pd.read_json(json_str, orient='index').reset_index()

    df = df[df['mine'].str.contains(mine)]
    df = df[df['subject'].str.contains(subject)]
    df = df[df['difficulty'].str.contains(difficulty)]
    df['keyword_check'] = df.apply(lambda x: keyword in x['question'].split(' '), axis=1)
    return df[df['keyword_check']]

如果您的json数据很复杂,具有不同的模式,并且非常大,那么您最好使用mongodb及其查询引擎
json结构的一些细节(可能是一个示例)会很有帮助

    • 编辑:**

你的JSON结构看起来相当简单,我建议你使用panda方法。进一步--要将JSON对象解析成python可理解的对象,我建议使用dataclassespydantic。这些允许你以更Python的方式与嵌套数据交互。添加一个示例(部分)如下:

from dataclasses import dataclass
from typing import List
import json

json_str = '''{
    "1": {
        "question": "What's the capital of Spain?",
        "subject": "",
        "date" : "",
        "timesright" : 2,
        "timeswrong" : 3,
        "difficulty": "",
        "keywords" : "geography, general knowledge",
        "explanation": "",
        "answers": [
            {
                "id": 1,
                "answer": "Paris",
                "is_correct": false
            },
            {
                "id": 2,
                "answer": "Madrid",
                "is_correct": true
            },
            {
                "id": 3,
                "answer": "Roma",
                "is_correct": false
            },
            {
                "id": 4,
                "answer": "Moscow",
                "is_correct": false
            }
        ]
    }
}'''

@dataclass
class Answer:
    id: int
    answer: str
    is_correct: bool

@dataclass
class Question:
    question: str
    subject: str
    date: str
    timesright: int
    timeswrong: int
    difficulty: str
    keywords: str
    explanation: str
    answers: List[Answer]

for question_id, question_dict in json.loads(json_str).items():
    question = Question(**question_dict)
    if question.difficulty == "high":
        print("found a difficult one!")

相关问题