Why do you need lambda to nest defaultdict?

家住魔仙堡 提交于 2019-12-07 02:01:18

问题


I am a bit confused on why you need a lambda function for nesting defaultdict

Why can't you do it like this?

test = defaultdict(defaultdict(list))

instead of

test = defaultdict(lambda:defaultdict(float))

回答1:


test = defaultdict(defaultdict(list))

Because defaultdict requires that you give it something that can be called to create keys for missing values. list is such a callable, but defaultdict(list) is not. It's a defaultdict instance, and you can't call a defaultdict.

The lambda is a function that, when called, returns a value that can be used in the dictionary, so it works.

Essentially, defaultdict(list) is going to be evaluated before your defaultdict is instantiated, and you want to defer that until a missing key is encountered. This is why a callable object (a type or a function) is used here.



来源:https://stackoverflow.com/questions/30609117/why-do-you-need-lambda-to-nest-defaultdict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!