首页 > 解决方案 > 寻找一种编写具有多种可能性的 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中有没有更好的方法来做到这一点?

标签: 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

推荐阅读