这是我的功能: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)
添加回答
举报
0/150
提交
取消