如果在python中出现条件,如何避免多个单位?

编程入门 行业动态 更新时间:2024-10-23 16:14:36
本文介绍了如果在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中出现条件,如何避免多个单位?

本文发布于:2023-10-18 10:50:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504015.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   条件   单位   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!