python中if else语句用法_在Python中避免使用嵌套的if else语句梯形图

当你不确切地知道如何描述它时,很难找到这个问题的答案......

处理一个相当深的(但是固定的)嵌套测试集的最惯用的方法是什么,你希望按顺序运行但是在第一个测试成功后立即终止?

而不是以下

选项1 :(导致压痕过多)def make_decision():

results = ... some code or function that returns a list or None

if results:

decision = random.choice(results)

else:

results = ... other code or function

if results:

decision = random.choice(results)

else:

results = ... other code or function

if results:

decision = random.choice(results)

else:

results = ... other code or function

if results:

decision = random.choice(results)

...etc.

else:

decision = None

print(decision)

return decision

选项2

另一种选择是尽早从函数返回,但我不确定这么多的回报分散在一起是好的做法,在这种情况下,我宁愿最后做一件事(例如print(decision))在返回之前:def make_decision():

results = ... some code or function that returns a list or None

if results:

return random.choice(results)

results = ... other code or function

if results:

return random.choice(results)

results = ... other code or function

if results:

return random.choice(results)

...etc.

else:

decision = None

return decision

选项3

最后,我可以使每个测试成为这里描述的单独函数,并迭代地调用它们,前提是每个测试函数都有相同的参数集。def test1(args):

...

def test2(args):

...

def test3(args):

...

def make_decision():

decision = None

for test in [test1, test2, test3, ...]:

results = test(args)

if results:

decision = random.choice(results)

break

print(decision)

return decision

这看起来最好,但我没有计划为每个测试创建一个函数,一些测试可以使用相同的函数但使用不同的参数完成,有些只是单行,而其他是多行。那么在开始循环之前我是否必须构建一个函数和参数列表?或者列出一些partial功能?

欢迎任何更好的建议(在我继续上面的选项3之前)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值