问题
Consider the snippet:
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
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.
回答1:
just loop on the condition/message couples for instance:
for condition,message in ((condition1,"message1"),(condition2,"message2"),(condition3,"message3")):
if condition:
list1.append(message)
if the conditions are exclusive, consider adding a break if one condition matches.
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]
回答2:
As a supplement of Jean-FrançoisFabre.
All conditions are satisfied
tmp = [message for condition, message in ((condition1, "message1"),
(condition2, "message2"),(condition3, "message3")) if condition]
Conditions are exclusive
tmp = next((message for condition, message in ((condition1, "message1"),
(condition2, "message2"), (condition3, "message3")) if condition), None)
来源:https://stackoverflow.com/questions/41501833/how-to-avoid-multiple-flat-if-conditions-in-python