试图了解python中的reduce功能

时间:2019-06-11 00:53:42

标签: python reduce

我最近收到了stackoverflow研究员关于上一个问题的答复,并且我尝试进行更多询问以了解该功能,但是以某种方式没有任何反应,因此我想在这里提出。

我想知道在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.replace?那不是字典吗?应该v.replace吗?此方法以某种方式起作用。我希望有人可以向我解释这是如何工作的,请尽可能提供更多详细信息。谢谢!

1 个答案:

答案 0 :(得分:1)

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函数上调用 this 会做什么。

for i in dictionary

循环将遍历字典中的每个键。它将把该键以及存储的ret(或第一次调用的initial参数)传递给您的函数。因此,您将获得每个键以及最初为"There istest at the cardboards"的字符串值,作为您的v(字典中的键,在i的扩展中称为reduce)和{ {1}}(长字符串,在k的扩展中称为ret)自变量。

请注意,reduce是全文字符串,而不是用作字典中键的字符串,而k是作为字典中键的单词。我在这里使用变量名vk只是因为您也这样做了。如评论中所述,在扩展的v或原始text函数中,worddef 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 functools.reduce作为其他两个参数,在函数f上运行dictionary函数,并观察输出。

相关问题