這是我的功能: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)我有許多類似的函數(shù),其中additonal_variable可以包含None.我真的很想避免用這樣的風(fēng)格來(lái)膨脹代碼庫(kù):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)我認(rèn)為這段代碼很難看并且難以維護(hù)。有沒(méi)有更好的方法或最佳實(shí)踐來(lái)避免使用這些長(zhǎng)的ifandelse語(yǔ)句?
Python 函數(shù):避免使用 if 子句進(jìn)行參數(shù)檢查
人到中年有點(diǎn)甜
2023-02-07 11:11:20