如果在python中出现条件,如何避免多个单位? [英] How to avoid multiple flat if conditions in python?

查看:83
本文介绍了如果在python中出现条件,如何避免多个单位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑代码段:

def check_conditions(range_of_numbers):
#method returns a list containing messages 
    list1 = []
    if condition1:
       list1.append("message1")
    if condition2:
       list1.append("message2")
    if condition3:
       list1.append("message3")
    try:
       for i in range_of_numbers:
           int(i)
    except ValueError:
        list1.append("message4")
    return message

仅当满足条件时,我才希望在with消息中有一个列表.我不使用多个if,因为它增加了代码的复杂性,并且每次添加新参数时,我最终都会添加新的if条件.

I want to have a list in the with messages only if the conditions were satisfied. I do not use multiple if's since it adds on to the code complexity and every time a new parameter is added I would end up adding a new if condition.

推荐答案

仅对条件/消息对进行循环:

just loop on the condition/message couples for instance:

for condition,message in ((condition1,"message1"),(condition2,"message2"),(condition3,"message3")):
    if condition:
       list1.append(message)

如果条件是排他性的,请考虑在一个条件匹配的情况下添加break.

if the conditions are exclusive, consider adding a break if one condition matches.

列表理解版本(虽然更"pythonic",但在首次条件匹配时无法中断):

list comprehension version (more "pythonic" but not possible to break on first condition match, though):

list1 = [message for condition,message in ((condition1,"message1"),(condition2,"message2"),(condition3,"message3")) if condition]

这篇关于如果在python中出现条件,如何避免多个单位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆