[英]Most pythonic way of approaching a multiple conditionals function
也許只有我一個人,但是我似乎幾乎每天都遇到這個問題。 我在很多地方都聽說過該功能應該緊湊且易於閱讀。
我經常遇到一種情況,即我有多個條件,它們都返回不同的值。 就像是。
def conditionals():
if something1:
return item1
if something2:
return item2
if something3:
return item3
...
隨着更多的條件,該函數不是緊湊的並且肯定是不可讀的。 我發現要使它更好的唯一方法是使每個項都具有特定的功能。 但是然后在我的代碼中,我覺得我有這么多的功能,無所不用其極。 無論如何,解決此問題的最佳方法是什么?
如果您的數據合適,則可以使用字典來存儲條件和操作之間的映射:
def conditionals(something):
somethings = {something1: item1, something2: item2, something3: item3}
try:
return somethings[something]
except KeyError:
return None
該字典還可以包含可以根據條件調用以執行操作的函數:
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()
如果您的條件和返回值不太長,例如
def f(x):
return (-x*x if x<0 else
0 if x<2 else
(x-2)**3 )
當然,可讀性是情人眼中的...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.