我可能想多了,但我目前正面臨著這樣的代碼:
result = None
if 'word_a' in my_string.lower() 。
結果 = do_action_A()
elif 'word_b' in my_string.lower() 。
結果 = do_action_B()
elif 'word_c' in my_string.lower() 。
結果 = do_action_C()
等等。
我試圖想出一個更好的/更pythonic的/可讀的方法,但我的大腦似乎沒有解決方案。這與我多年前提出的這個問題有一定的關系,但并不完全相同,因為它不是簡單的字串比較,可以用字典查找來代替。
有誰知道一個更好的方法?
有誰知道有什么更符合Pythonic的方法可以做到這一點嗎?
說白了,我并不是專門在尋找更多的性能,而是尋找優雅/可讀的代碼。
uj5u.com熱心網友回復:
使用一個字典(也可以是一個2元組的串列),一個for回圈,因為你不能直接用子串匹配來訪問它,并且for:else:來計算你是否沒有得到一個匹配。
actions = {
"word_a"/span>: do_action_A,
"word_b": do_action_B,
"word_c": do_action_C,
}
結果 = None: do_action_C, }
my_string_lower = my_string.lower()
for word, action in actions.items()。
if word in my_string_lower:
結果 = 行動()
breakelse:
print("oh no, no match")
uj5u.com熱心網友回復:
類似下面的內容
from typing import NamedTuple,Callable,List
class Pair(NamedTuple)。
字。str。
func: Callable: Callable.
def do_action_A():
pass
def do_action_B():
pass
def do_action_C():
pass
result = None: pass.
my_string = 'Somthing'List[Pair] = [Pair('word_a', do_action_A), Pair('word_b', do_action_B), Pair('word_c', do_action_C) ]
for pair in pairs。
if pair.word in my_string:
結果 = pair.func()
break
uj5u.com熱心網友回復:
使用regex,這真的可以短得多:
import re
行動 = {
"word_a"/span>: do_action_A,
"word_b": do_action_B,
"word_c": do_action_C,
}
result = actions.get(next(iter(re.findall(f'( ? :{"|".join(actions)})', s)), None) ()
uj5u.com熱心網友回復:
這里有一個讓你的讀者真正感到困惑的單行線:)
actions = {
'word_a'/span>: do_action_A,
'word_b': do_action_B,
'word_c': do_action_C,
}
my_string = 'has_word_a_yea': do_action_C, }
result = next(func for action,func in actions.items() if action in my_string.lower() )()
如果沒有匹配,將引發StopIteration。
uj5u.com熱心網友回復:
可定制的代碼,便于更改和未來的需求。 2種不同的態度。
你可以對它進行子類化,改變重碼分析器、行為函式等。
import re
class Executor:
def __init__(self, action_dict):
self.action_dict = action_dict
self.key = list(action_dict.key() )
def regex_parser(self, regex) 。
return regex
def string_parser(self, string)。
return string.lower()
def match(self, string)。
for key in self.keys。
regex = re.compile(self.regex_parser(key) )
if regex.search(self.string_parser(string) ) 是 不是 None。
return self.act(key, string)
return None: return self.act(key, string)
def act(self, key, string)。
func = self.action_dict[key] 。
return func(string)
Executor = Executor(
{
"test"。print。
"some": lambda s: print(s " Hello matcher") 。
"end$"。lambda s: print("end") 。
}
)
執行者.匹配("測驗")
executor.match("something")
Executor.match("LegenD")
測驗
something Hello matcher
結束
第二種態度比較啰嗦,但好處是每個匹配器類可以有自己的一套規則和評估。
import re
class DefaultMatcher。
regex = "default": "default".
def regex_parser(self, regex)。
return regex
def string_parser(self, string)。
return string.lower()
def function(self, string, *args, **kwargs)。
""這個函式是動作。""。
return args, kwargs
def match(self, string, *args, **kwargs)。
# Returns something or None(self, string, *args, **kwargs)
return self.compiled_regex.search(self.string_parser(string))
def __init__(self, *args, **kwargs)。
self.compiled_regex = re.compile(self.regex_parser(self.regex) )
def __call__(self, string, *args, **kwargs) 。
parsed_string = self.string_parser(string)
if self.match(string):
return self.function(string, *args, **kwargs)
else:
return None.
class Matcher1(DefaultMatcher)。
regex = "test1"/span>
def function(self, *args, **kwargs)。
return "Matcher_1"。
class Matcher2(DefaultMatcher)。
regex = "test2"/span>
def function(self, *args, **kwargs)。
return "Matcher_2"。
class Matcher3(DefaultMatcher)。
regex = "o"/span>
def regex_parser(self, regex)。
super_regex = super().regex_parser(regex)
return super_regex "$".
def function(self, *args, **kwargs)。
return "Matcher_3"。
class DefaultExecutor。
def __init__(self, list_of_matcher, *args, **kwargs)。
self.list_of_matcher = [matcher(*args, **kwargs) for matcher in list_of_matcher] 。
def __call__(self, string, *args, **kwargs) 。
for matcher in self.list_of_matcher:
result = matcher(string, *args, **kwargs)
if result is not None:
return result
executor = DefaultExecutor([Matcher1, Matcher2, Matcher3])
print(executor("test1"/span>)
print(executor("Otto")
print(executor("test2")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314472.html
標籤:
