我有幾個字串處理函式,如:
def func1(s):
return re.sub(r'\s', "", s)
def func2(s):
return f"[{s}]"
...
我想將它們組合成一個管道函式:my_pipeline(),以便我可以將其用作引數,例如:
class Record:
def __init__(self, s):
self.name = s
def apply_func(self, func):
return func(self.name)
rec = Record(" hell o")
output = rec.apply_func(my_pipeline)
# output = "[hello]"
目標是my_pipeline用作引數,否則我需要一一呼叫這些函式。
謝謝你。
uj5u.com熱心網友回復:
您可以撰寫一個簡單的工廠函式或類來構建管道函式:
>>> def pipeline(*functions):
... def _pipeline(arg):
... restult = arg
... for func in functions:
... restult = func(restult)
... return restult
... return _pipeline
...
>>> rec = Record(" hell o")
>>> rec.apply_func(pipeline(func1, func2))
'[hello]'
uj5u.com熱心網友回復:
您可以創建一個呼叫這些函式的函式:
def my_pipeline(s):
return func1(func2(s))
uj5u.com熱心網友回復:
使用函式串列(因此您可以在其他地方組裝這些函式):
def func1(s):
return re.sub(r'\s', "", s)
def func2(s):
return f"[{s}]"
def func3(s):
return s 'tada '
def callfuncs(s, pipeline):
f0 = s
pipeline.reverse()
for f in pipeline:
f0 = f(f0)
return f0
class Record:
def __init__(self, s):
self.name = s
def apply_func(self, pipeline):
return callfuncs(s.name, pipeline)
# calling order func1(func2(func3(s)))
my_pipeline = [func1, func2, func3]
rec = Record(" hell o")
output = rec.apply_func(my_pipeline)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487560.html
上一篇:按名稱合并多對列
