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

查看:179
本文介绍了python defaultdict:0 vs. int和[] vs list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

传递 int lambda:0 之间是否有什么区别?或列表 lambda:[]

Is there any difference between passing int and lambda: 0 as arguments? Or between list and lambda: []?

看起来他们做同样的事情:

It looks like they do the same thing:

from collections import defaultdict
dint1 = defaultdict(lambda: 0)
dint2 = defaultdict(int)
dlist1 = defaultdict(lambda: [])
dlist2 = defaultdict(list)

for ch in 'abracadabra':
    dint1[ch] += 1
    dint2[ch] += 1
    dlist1[ch].append(1)
    dlist2[ch].append(1)

print dint1.items()
print dint2.items()
print dlist1.items()
print dlist2.items()
## -- Output: --
[('a', 5), ('r', 2), ('b', 2), ('c', 1), ('d', 1)]
[('a', 5), ('r', 2), ('b', 2), ('c', 1), ('d', 1)]
[('a', [1, 1, 1, 1, 1]), ('r', [1, 1]), ('b', [1, 1]), ('c', [1]), ('d', [1])]
[('a', [1, 1, 1, 1, 1]), ('r', [1, 1]), ('b', [1, 1]), ('c', [1]), ('d', [1])]


$ b

but are there any cases where they'll have different behavior, or is it merely a notational difference?

推荐答案

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

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.

例如,

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

这篇关于python defaultdict:0 vs. int和[] vs list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆