[英]reduce not working for collections.defaultdict?
在以下情況下,為什么reduce()
無法與defaultdict
對象一起使用:
>>> from collections import defaultdict
>>> d = defaultdict(lambda: defaultdict(int))
>>> reduce(dict.get, [1,2], d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'get' requires a 'dict' object but received a 'NoneType'
上面的reduce
等效於d[1][2]
,所以我期望0
,即默認返回值作為輸出,但是我得到了NoneType
異常。
如果我使用d[1][2]
則如下所示:
>>> d[1][2]
0
我做錯什么了嗎?
如果不存在鍵, 即使對於defaultdict
對象 , dict.get()
將返回None
。
這是因為dict.get()
的工作是在缺少鍵時返回默認值。 如果沒有,您將永遠無法返回不同的默認值( dict.get()
的第二個參數):
>>> from collections import defaultdict
>>> d = defaultdict(lambda: defaultdict(int))
>>> d.get(1, 'default')
'default'
換句話說,您的reduce(dict.get, ..)
函數不等同於d[1][2]
表達式。 它等效於d.get(1).get(2)
,它以完全相同的方式失敗:
>>> d = defaultdict(lambda: defaultdict(int))
>>> d.get(1).get(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'get'
如果要依賴自動插入行為,請使用dict.__getitem__
:
>>> reduce(dict.__getitem__, [1,2], d)
0
表達式d[1]
直接轉換為d.__getitem__(1)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.