python - 寻找一种编写具有多种可能性的 if 结构的好方法
问题描述
我正在使用 if 语句从数据库中检索某些内容。但它有多个条件,我当前的实现有效,但正在寻找更好的选择。
data = get(col1=a,
col2=b,
col3=c
)
if not data:
#fall to 2nd option
data = get(col1=a,
col2=b
)
if not data:
#fall to 3rd option
data = get(col1=a,
col3=c
)
if not data:
#fallback to 4th option
data = get(col1=a
)
get 函数具有从 mysql 数据库中检索行的代码。python中有没有更好的方法来做到这一点?
解决方案
这有点干净,您可以轻松地向其中添加新案例:
args = [dict(col1=a,col2=b,col3=c),
dict(col1=a,col2=b),
dict(col1=a,col3=c),
dict(col1=a)]
for arg_dict in args:
data = get( **arg_dict )
if data:
break
推荐阅读
- java - 启动时未触发通知
- c# - 在 c# windows 应用程序表单的仪表板中登录后如何获取用户名
- c# - 需要更新拖曳实体时无法访问 asp core 3 中的已处置对象
- angular - 具有空值的 switchMap
- python - 如何使用 Django 进行表单验证?
- java - 如何在函数中的子字符串和比较器中的两个值中实现二进制搜索?
- pytorch - pytorch F.cross_entropy 不对权重应用梯度
- iis - SharePoint 2019 - 添加自定义响应标头不起作用
- javascript - 使用 render props 访问 refs
- machine-learning - 卷积神经网络中的池化不会在特征检测中失去精度吗?