>我最近收到了堆栈溢出研究员对我之前问题的回答,我试图询问更多以了解该功能,但不知何故没有回应,所以我想在这里问它。
我想知道 lambda 中使用的 k 和 v 代表什么?我以为是这样代表的...
k = dictionary ?
v = string ? # Did I understand it correctly?
dictionary = {"test":"1", "card":"2"}
string = "There istest at the cardboards"
from functools import reduce
res = reduce(lambda k, v: k.replace(v, dictionary[v]), dictionary, string)
由于我们使用 lambda,因此它会循环这两个变量中的每个元素。但为什么要 k.替换?这不是字典吗?它应该是v.replace吗?不知何故,这种方法有效。我希望有人能向我解释这是如何工作的,如果可能的话,请提供更多细节。谢谢!
reduce
等效于重复调用函数。
本例中的函数是 lambda,但 lambda 只是一个匿名函数:
def f(k, v):
return k.replace(v, dictionary[v])
reduce
本身的定义是(几乎——这里的None
默认值不太正确,也不是len
测试):
def reduce(func, seq, initial=None):
if initial is not None:
ret = initial
for i in seq:
ret = func(ret, i)
return ret
# initial not supplied, so sequence must be non-empty
if len(seq) == 0:
raise TypeError("reduce() of empty sequence with no initial value")
first = True
for i in seq:
if first:
ret = i
first = False
else:
ret = func(ret, i)
return ret
因此,问问自己,当调用 lambda 函数时,这会做什么。 这:
for i in dictionary
循环将遍历字典中的每个键。 它会将该键以及存储的ret
(或第一次调用的initial
参数)传递给您的函数。 因此,您将获得每个键,加上最初"There istest at the cardboards"
的字符串值,作为您的v
(字典中的键,在reduce
的扩展中称为i
)和k
(长字符串,在reduce
的扩展中称为ret
)参数。
请注意,k
是全文字符串,而不是字典中用作键的字符串,而v
是字典中的键。我在这里使用了变量名称k
和v
,只是因为您也这样做了。 如注释中所述,text
和word
可能是扩展def f(...)
或原始lambda
函数中更好的变量名称。
跟踪代码执行
尝试相同的代码,除了:
def f(k, v):
return k.replace(v, dictionary[v])
你把它写成:
def f(text, word):
print("f(text={!r}, word={!r})".format(text, word))
replacement = dictionary[word]
print(" I will now replace {!r} with {!r}".format(word, replacement))
result = text.replace(word, replacement)
print(" I got: {!r}".format(result))
return result
在函数f
上运行functools.reduce
函数,dictionary
和string
作为其他两个参数并观察输出。