python - 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)
我认为这段代码丑陋且难以维护。有没有更好的方法或最佳实践来避免使用这些长if
和else
语句?
解决方案
您可以将块最小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)
推荐阅读
- android - 清单合并失败:Android Studio 多个错误
- c# - ShowDialog 在 Windows Server 2016 上花费了太多时间
- javascript - 链接重定向到另一个页面和特定选项卡
- oracle - INITIAL_VALUE 上的 SET_ITEM_PROPERTY 不起作用
- git - Azure DevOps 默认权限
- bitwise-xor - 如何在按位异或中反转我的公式以获得 53 的值?
- javascript - 反应和文本输入 - 使用 onBlur 或 onChange?
- apache-kafka - 更改默认端口的 Apache Zookeeper 问题
- python - 为什么无论如何我都会不断收到“正在关闭...”作为输出?
- ruby - 如何更改 gemfile.lock 捆绑的版本