[英]Most pythonic way of approaching a multiple conditionals function
Maybe it is just me, but I seem to come across this problem on almost a daily basis. 也许只有我一个人,但是我似乎几乎每天都遇到这个问题。 I've heard in many places that function should be compact and easy to read.
我在很多地方都听说过该功能应该紧凑且易于阅读。
I often have a scenario where I have multiple conditionals which all return different values. 我经常遇到一种情况,即我有多个条件,它们都返回不同的值。 Something like.
就像是。
def conditionals():
if something1:
return item1
if something2:
return item2
if something3:
return item3
...
With a lot more conditionals, the function is not compact and certainly not readable. 随着更多的条件,该函数不是紧凑的并且肯定是不可读的。 The only way I found to make this better is to make a function specific to each item to return.
我发现要使它更好的唯一方法是使每个项都具有特定的功能。 But then in my code, I feel like I have so many functions for nothing.
但是然后在我的代码中,我觉得我有这么多的功能,无所不用其极。 Anyway, what is the best way to solve this?
无论如何,解决此问题的最佳方法是什么?
If your data is amenable, you could use a dictionary to store the mapping between conditions and actions: 如果您的数据合适,则可以使用字典来存储条件和操作之间的映射:
def conditionals(something):
somethings = {something1: item1, something2: item2, something3: item3}
try:
return somethings[something]
except KeyError:
return None
this dictionary could also contain functions that could be called to take an action, based on a condition: 该字典还可以包含可以根据条件调用以执行操作的函数:
def conditionals(somecondition):
conditions = {condition1: action1, condition2: action2, condition3: action3}
try:
conditions[somecondition]()
except KeyError:
print(f"action not found for {somecondition}")
def action1():
do_this()
def action2():
do_that()
def action3():
do_this()
do_that()
If your conditions and return values are not too long something like 如果您的条件和返回值不太长,例如
def f(x):
return (-x*x if x<0 else
0 if x<2 else
(x-2)**3 )
Of course, readability is in the eye of the beholder... 当然,可读性是情人眼中的...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.