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

python defaultdict:0 vs. int和[] vs list,第1张

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

defaultdict
需要的只是一个可调用对象,该对象返回不带参数调用时应用作默认值的对象。

如果要调用

int
构造函数,它将返回
0
,如果要调用
lambda:0
,它将返回
0
。与列表相同。唯一的区别是,构造函数将始终使用其逻辑来创建对象。一个lambda,如果您选择这样做,则可以添加其他逻辑。

例如,

# alternating between `0` and `[]`from itertools import countfactory = lambda c=count(): 0 if next(c) % 2 else []superdict = defaultdict(factory)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5601881.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存