我还没有找到一个答案,这是否合法。它是一个在字符串中查找和替换所有“变量”(以v_开头的单词)的函数。由于"if“子句的必要性,我不能使用lambda,因为替换函数需要多个行。
def fillin(template, dictionary):
result = re.sub(r'v_([a-z_]+)', def(match):
variable = match.group(1)
if not variable in dictionary:
return match # don't replace nuthin'
return dictionary[variable],
Scene )
return result它获取本文中以v_开头的所有字符串,然后查看字符串的其余部分以获得“变量名”,在字典中查找变量名,并将字符串替换为查找的值。
我不能使用lambda,因为在其中我需要一个"if key字典“子句来防止字典中的查找错误。
是否没有方法将def用于匿名函数?
发布于 2022-05-07 21:46:57
我想这个lambda会对你有用的。
lambda match: match if not match.group(1) in dictionary else dictionary[match.group(1)]发布于 2022-05-07 21:58:04
您可以使用lambda,如果使用dictionary.get(x.group(1), x.group()),仍然可以保持它的简短性。
re.sub(r'v_([a-z_]+)', lambda x: dictionary.get(x.group(1),x.group()), text)import re
text = "aaa v_abc v_def"
dictionary = { 'abc':'yes' }
print( re.sub(r'v_([a-z_]+)', lambda x: dictionary.get(x.group(1),x.group()), text) )
# => aaa yes v_def发布于 2022-05-07 21:59:31
在调用“re.sub”之前定义函数,并将函数作为正常参数传递。"def“声明为函数提供了一个名称--它引用函数的方式与内嵌"lambda”表达式所做的一样。
def replacer(match):
variable = match.group(1)
if not variable in g_dictionary:
return match # don't replace nuthin'
return dictionary[variable]
def fillin(template, dictionary):
global g_dictionary
g_dictionary
result = re.sub(r'v_([a-z_]+)', replacer, Scene)
return result上面的示例将字典重新分配到一个全局变量,以便可以在其他函数中看到它。更常见的方法是定义嵌套函数,如下面的示例所示。
在这种情况下,您需要访问“字典”(它是外部作用域中的一个变量),您可以定义嵌套在replacer中的fillin --这正是定义lambda函数时发生的情况。:
def fillin(template, dictionary):
def replacer(match):
variable = match.group(1)
if not variable in dictionary:
return match # don't replace nuthin'
return dictionary[variable]
result = re.sub(r'v_([a-z_]+)', replacer, Scene)
return resulthttps://stackoverflow.com/questions/72156540
复制相似问题