首页 > 解决方案 > Python 函数:避免使用 if 子句进行参数检查

问题描述

这是我的功能:

def save_to_mongo(self, df, collection, additional_variable):
    for index, row in df.iterrows():
        result = row.to_dict()
        collection.update_one(
            {"_id": str(row['date']) + "_" + str(row['sector']) + "_" + str(row['caseid']) + str(row[additional_variable])},
            {
                '$set': result
            },
            upsert=True)

我有许多类似的函数,其中的参数additonal_variable可以是None.

我真的很想避免用这样的风格膨胀代码库:

if additional_varibale is None:
    collection.update_one(
        {"_id": str(row['date']) + "_" + str(row['sector']) + "_" + str(row['caseid'])},
        {
            '$set': result
        },
        upsert=True)
else:
    collection.update_one(
        {"_id": str(row['date']) + "_" + str(row['sector']) + "_" + str(row['caseid']) + str(row[additional_variable])},
        {
            '$set': result
        },
        upsert=True)

我认为这段代码丑陋且难以维护。有没有更好的方法或最佳实践来避免使用这些长ifelse语句?

标签: pythonpandasif-statementpymongo

解决方案


您可以将块最小if else化为 -

additional_varibale = '' if additional_varibale is None else str(row[additional_variable])
    
collection.update_one(
    {"_id": str(row['date']) + "_" + str(row['sector']) + "_" + str(row['caseid']) + additional_varibale},
    {
        '$set': result
    },
    upsert=True)

推荐阅读