我一直在玩默认字典而且我很困惑
为什么这不起作用:
例1
def hi(name):
return "hi " + name
a = defaultdict(hi)
print(a["hello"]("jane"))
Run Code Online (Sandbox Code Playgroud)
输出示例1
TypeError: hi() missing 1 required positional argument: 'name'
Run Code Online (Sandbox Code Playgroud)
但这样做:
例2
def hi(name):
return "hi " + name
a = {"hello":hi}
print(a["hello"]("jane"))
Run Code Online (Sandbox Code Playgroud)
输出示例2
hi jane
Run Code Online (Sandbox Code Playgroud)
也使用lambda会使它工作
例3
def hi(name):
return "hi " + name
a = defaultdict(lambda: hi)
print(a["hello"]("jane"))
Run Code Online (Sandbox Code Playgroud)
输出示例 3
hi jane
Run Code Online (Sandbox Code Playgroud)
为什么示例1返回错误而示例3没有?
这是怎么回事?
当defaultdict没有找到键时,它会调用没有任何参数的函数.同
def hi(name):
return "hi " + name
a = defaultdict(hi)
a["hello"]
Run Code Online (Sandbox Code Playgroud)
,hi已被调用,虽然您希望以后才能调用它.由于hi默认情况下没有任何参数调用,您会看到手动运行时看到的相同错误hi(),即TypeError抱怨错误的参数计数.
写出lambda的另一种方法(仅用于教学目的)将是
def hi(name):
return "hi " + name
def make_hi():
return hi
a = defaultdict(make_hi)
print(a["hello"]("jane"))
Run Code Online (Sandbox Code Playgroud)
在这里,访问a["hello"]调用make_hi,然后返回hi,然后使用参数调用("jane").