根据 JSON 中的条件筛选 python 中的对象

Filter objects in python, based on criteria in JSON

我有一个相对简单的用例,我需要加载符合特定条件的车辆类型。此标准显示在“sample_input”变量中。

现在我需要展示符合正确标准的汽车。我正在读取我的 car 数据库 JSON,然后创建汽车对象并将它们添加到我的 carDatabase 列表中,我需要从这个列表中 select 符合用户要求的汽车。

所以基本上发生的事情是我在 Main.Py

中加载了一个简单的 sample_input 变量

代码应该这样做,但它没有(总是欢迎更好的实现)

检查Name是否为空[];如果是,继续前进;如果不是,则搜索具有相同名称的汽车,移至下一个标准,即原产国,检查它是否为空,如果不是,则寻找具有名称和原产国的汽车,以及其他标准等等。

import json

from Vehicle import Vehicle

sample_input = {
    "Name": [],
    "country of origin": ["france", "uk"],
    "transmission": [],
    "body type": ["coupe"],
    "drive type": [],
    "doors": [],
    "fuel type": []
}


def test():
    with open("data.json") as omapper:
        data = json.load(omapper)
        Database= []
        for i in data["vehicles"]:
            name = i["Name"]
            origin = i["country of origin"]
            transmission = i["transmission"]
            bodytype = i["body type"]
            drivetype = i["drive type"]
            doors = i["doors"]
            fueltype = i["fuel type"]
            vehicle= Vehicle(name,origin,transmission,bodytype,drivetype,doors,fueltype)
            Database.append(car)

    UserOutput = []

    for vehicles in Database:
        if vehicles.origin in sample_input["country of origin"] and vehicles.body_type in sample_input["body type"] and vehicles.doors in sample_input["doors"] != "":
            print(vehicle.name)


if __name__ == "__main__":
   test()

Vehicle.py:型号class

 class Vehicle:
        def __init__(self, name, origin, transmission, body_type, drive_type, doors, fuel_type):
            self.name = name
            self.origin = origin
            self.transmission = transmission
            self.body_type = body_type
            self.drive_type = drive_type
            self.doors = doors
            self.fuel_type = fuel_type

车辆JSON:我的应用程序支持的所有车辆。

  {
    "attributes": {
        "country of origin": ["japan", "america", "germany", "south korea", "italy", "sweden"],
        "transmission": ["automatic", "manual"],
        "body type": ["hatchback", "sedan", "SUV", "ute", "coupe", "convertible", "van"],
        "drive type": ["RWD", "FWD", "4WD"],
        "doors": ["4 door", "2 door"],
        "fuel type": ["petrol", "diesel", "electric", "hybrid"]
    },
    "vehicles": [
    {
        "Name": "studebaker dictator",
        "country of origin": "america",
        "transmission": "manual",
        "body type": "sedan",
        "drive type": "RWD",
        "doors": "2 door",
        "fuel type": "petrol"
    },
    {
        "Name": "mitsubishi zero",
        "country of origin": "japan",
        "transmission": "manual",
        "body type": "hatchback",
        "drive type": "FWD",
        "doors": "2 door",
        "fuel type": "petrol"
    },
   ...
    ]
    }

您只需要详细说明您在散文阐述中已经列出的条件。

for vehicle in Database:
    if (not sample_input["country of origin"] or vehicle.origin in sample_input["country of origin"]) and (
        not sample_input["transmission"] or vehicle.transmission in sample_input["transmission"]) and (
        not sample_input["body type"] or vehicle.body_type in sample_input["body type"]
    ):
        print(vehicle.name)
如果 sample_input["x"] 是一个空列表,

not sample_input["x"] 将是 True;如果不是,我们检查 vehicle.x 是否在列表中。

另请注意我是如何将循环变量更改为单数形式的;我们一次检查一个 vehicle

如果您需要能够在循环中访问每个可能的属性,请尝试类似

class Vehicle:
    # ...
    def attr_map(self, label):
        """
        Map a label like 'country of origin' to
        the corresponding internal attribute,
        and return that.
        """
        return {
            'country of origin': self.origin,
            'transmission': self.transmission,
            'body type': self.body_type,
            # ... etc
        }[label]

然后循环遍历您想要的属性:

for vehicle in Database:
    vehicle_selected= True
    for attr in sample_input:
        if sample_input[attr] and vehicle.attr_map(attr) not in sample_input[attr]:
            vehicle_selected = False
            break
    if vehicle_selected:
        print(vehicle.name)

如果您愿意,可以在 JSON 导入循环中对 i 执行类似的操作;那么将键映射到属性的方法不是必需的,您可以简单地检查... and i[attr] in sample_input[attr]