2 回答

TA贡献1848条经验 获得超10个赞
你根本不需要使用re.compile,真的。re.match和朋友无论如何在内部缓存上次使用的正则表达式模式。
在这里,switcher已从case函数中重构出来,因此不会在每次调用时重新计算;此外,我们使用dict.items()同时获取模式和值。
switcher = {
'bronze': 10,
'carbon': 16,
}
def case(string):
for pattern, value in switcher.items():
if re.match(pattern, string, flags=re.IGNORECASE):
return value
return "Invalid: " + string
但是,根据您的示例,尚不清楚您是否需要正则表达式,或者您是否只需要不区分大小写的子字符串匹配,在这种情况下,将测试字符串小写在计算上会更便宜,然后只需使用if str1 in str2,就像这样(假设与switcher上一个示例中的 dict相同。)
def case_no_re(string):
l_string = string.lower()
for pattern, value in switcher.items():
if pattern in l_string:
return value
return "Invalid: " + string
添加回答
举报