Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

Condensed mutltiple if condition is equal to something in python

I try to select keys and values in a json file and calculate average values. If a key is equal to a certain value, I want to take them and to calculate the average value.

for total in data_total:
    object_id = total["objectID"]
    model = total["modele"]
    marque = total["marque"]
    cote_2020 = total["cote"]["cote_2020"]["cote_2020_eu"]["cote_2020_base_eu"]
    #models list
    if model == "Ace":
        model_ace = []
        model_cote_ace = cote_2020
        model_ace.append(model_cote_ace)
        mean_ace = statistics.mean(model_ace)
        mean_ace = round(mean_ace)
        cote_2020_ace = mean_ace

An sample of the json file:

    {
        "objectID": 10028,
        "modele": "Ace",
        "cote_actual": {
            "cote_actual_eu": {
                "cote_actual_base_eu": 342327
            },
        },
     },
{
        "objectID": 10029,

        "modele": "Ace",
        "cote_actual": {
            "cote_actual_eu": {
                "cote_actual_base_eu": 20000
            },
        },
     

But I have thousands of different models. Have I to create thousands of if model == something conditions and calculate average values based on models ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If most of the calculations are the same, and you are customizing the calculation for only a handful of the models, a dictionary with functions you can call makes sense:

def default(entry):
  # Pass in total, or whatever object makes sense and perform calculations.
  result = 0  # actually figure out the result here
  return result

def ace(entry):
  # Ace instances need special handling
  result = 12  # customize this calculation somehow
  return result

funcs = {'Ace': ace}

for total in data_total:
  modele = total['modele']
  mean = funcs.get(modele, default)(total)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...