【问题标题】:Python function: Avoid using if clauses for parameter checkPython 函数:避免使用 if 子句进行参数检查
【发布时间】:2020-10-19 09:29:06
【问题描述】:

这是我的功能:

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 语句?

【问题讨论】:

    标签: python pandas if-statement pymongo


    【解决方案1】:

    您可以将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)
    

    【讨论】:

    • 谢谢,不知道python中存在这种三元运算符:)
    • 另外,'' if not additional_variable else str(row[additional_variable])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 2022-05-18
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多