python defaultdict: 0 vs. int and [] vs list

做~自己de王妃 提交于 2019-11-30 06:05:37

All that defaultdict requires is a callable object that will return what should be used as a default value when called with no parameters.

If you were to call the int constructor, it would return 0 and if you were to call lambda: 0, it would return 0. Same with the lists. The only difference here is that the constructor will always use it's logic to create the object. A lambda, you could add additional logic if you chose to do so.

e.g.,

# alternating between `0` and `[]`
from itertools import count
factory = lambda c=count(): 0 if next(c) % 2 else []
superdict = defaultdict(factory)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!