我有一個帶有 x 布爾引數的函式,如下所示:
def generic_function(input_string: str, a = True, b = True, c = True, d = True):
'''A generic function that applies a series of action
to a string'''
if a == False and b == True and c == True and d == True:
input_string = action_d(action_c(action_b(input_string)))
else if a == False and b == False and c == True and d == True:
input_string = action_d(action_c((input_string))
#etc.
return input_string
我想避免必須專門指定每個條件并使我的代碼不那么冗長。
有沒有更好、更優雅的方法來做到這一點?需要明確的是:原始函式是一個類的一部分,它定義了一系列函式并將其應用于文本以提取一些資料。例如,action_a 是一個 emojis 洗掉函式,action_b 是一個分詞器,等等。
uj5u.com熱心網友回復:
您可以做的一件事基本上是將所有布林值的可迭代物件傳遞給all內置函式,這肯定會使您的代碼看起來更干凈,因為您將所有條件組合在一起,如果布林值組合在一起and,您可以使用,或者您可以組合,具體取決于根據你的條件。anyorallany
def generic_function(input_string: str, a = True, b = True, c = True, d = True):
'''A generic function that applies a series of action
to a string'''
if all((not a,b,c,d,)):
input_string = action_d(action_c(action_b(input_string)))
elif all((not a, not b, c, d)):
input_string = action_d(action_c((input_string))
#etc.
return input_string
uj5u.com熱心網友回復:
您不必做出所有可能的組合。由于邏輯是在前一個函式 (g°f) 的回傳上應用一個函式,因此使用一系列 ofif很好并且完全等效。
def generic_function(input_string: str, a=True, b=True, c=True, d=True):
if a:
input_string = action_a(input_string)
if b:
input_string = action_b(input_string)
if c:
input_string = action_c(input_string)
if d:
input_string = action_d(input_string)
return input_string
uj5u.com熱心網友回復:
我們可以使用一些標準庫并獲得這個非常優雅的(恕我直言)解決方案:
from functools import reduce
from itertools import compress
def generic_function(input_string: str, a = True, b = True, c = True, d = True):
funcs = compress([action_a, action_b, action_c, action_d],[a,b,c,d])
return reduce(lambda x,y: y(x), funcs, input_string)
讓我們測驗一下:
action_a = lambda a: a 'a'
action_b = lambda b: b 'bb'
action_c = lambda c: c 'ccc'
action_d = lambda d: d 'dddd'
generic_function('test_') # 'test_abbcccdddd'
generic_function('test_', a=False, c=False) # 'test_bbdddd'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516490.html
