gpt4 book ai didi

python - defaultdict、函数和 lambda

转载 作者:太空狗 更新时间:2023-10-30 02:43:37 26 4
gpt4 key购买 nike

我一直在玩默认字典,我很困惑

为什么这不起作用:

示例 1

def hi(name):
return "hi " + name

a = defaultdict(hi)
print(a["hello"]("jane"))

输出示例 1

TypeError: hi() missing 1 required positional argument: 'name'

但这确实:

例子2

def hi(name):
return "hi " + name

a = {"hello":hi}
print(a["hello"]("jane"))

输出示例 2

hi jane

也可以使用 lambda 来实现

示例 3

def hi(name):
return "hi " + name

a = defaultdict(lambda: hi)
print(a["hello"]("jane"))

输出示例 3

hi jane

为什么示例 1 返回错误而示例 3 没有?

这是怎么回事?

最佳答案

当 defaultdict 找不到键时,它会调用不带任何参数的函数。与

def hi(name):
return "hi " + name

a = defaultdict(hi)
a["hello"]

, hi 已经被调用了,尽管你希望它稍后被调用。由于 hi 被 defaultdict 调用时没有任何参数,您会看到与手动运行 hi() 时相同的错误,即 TypeError 提示参数计数不正确。

另一种写出 lambda 的方法(仅用于教学目的)是

def hi(name):
return "hi " + name

def make_hi():
return hi

a = defaultdict(make_hi)
print(a["hello"]("jane"))

在这里,访问 a["hello"] 调用 make_hi,然后返回 hi,然后用参数调用(“简”)

关于python - defaultdict、函数和 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com