簡體   English   中英

減少條件數量

[英]Reduce number of conditions

我在函數中有這么長的條件列表:

if x == "a":
    return function_a()
elif "b" in x:
    return function_b()
elif x == "c string":
    return function_c()
elif x == "d string":
    return function_d()
else:
    function_e()

我怎樣才能簡化它,以便我可以降低我的功能的認知復雜性?

你可以這樣做:

def function_a():
    print("First function")
    
def function_b():
    print("Second function")
    
x = 'b'
fns = {'a': function_a, 'b': function_b}
fns[x]()

Python 沒有 switch 語句,因此常見的替代方法是使用字典來“選擇”要采用的選項。 在此示例中,您期望的值a,b,c,d...是字典中的鍵,相應的函數是該鍵的值。

要執行正確的函數,您只需要使用返回函數的fns[x]訪問字典,然后使用()括號調用該函數。

這是我對此的看法:

def function_a():
  return 'a'

def function_b():
  return 'b'

def function_c():
  return 'c'

def function_d():
  return 'd'

def function_e():
  print('e')

x = 'b'

L = {
  'a': function_a(),
  'c string': function_c(),
  'd string': function_d()
}

def reduced():
  try:
    L[x]()
  except KeyError:
    if 'b' in x:
      return function_b()
    else:
      function_e()

print(reduced())

如果有人可以改進它嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM