试着理解python中reduce的功能

2024-04-18 13:44:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近收到了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代替?那不是一本字典吗?它应该是v.replace吗?不知怎么的,这种方法是有效的。我希望有人能向我解释这是如何工作的,如果可能的话,请提供更多的细节。谢谢您!你知道吗


Tags: lambda函数testreducestringdictionaryitcard
1条回答
网友
1楼 · 发布于 2024-04-18 13:44:52

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是字典键的单词。我在这里使用变量名kv,只是因为您也这么做了。如注释中所述,textword在扩展的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函数,将dictionarystring作为其他两个参数,并观察输出。你知道吗

相关问题 更多 >