亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 函數:避免使用 if 子句進行參數檢查

Python 函數:避免使用 if 子句進行參數檢查

人到中年有點甜 2023-02-07 11:11:20
這是我的功能: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)我認為這段代碼很難看并且難以維護。有沒有更好的方法或最佳實踐來避免使用這些長的ifandelse語句?
查看完整描述

1 回答

?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

您可以將塊最小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)


查看完整回答
反對 回復 2023-02-07
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號