首页 > 解决方案 > defaultdict 中未定义键的条件

问题描述

我是 python 新手,我想在其中的集合模块中使用 defaultdict 编写代码,如下所示: defaultdict (lambda:'0') 但我只希望那些未定义键的值为 0,其中键大于 0 喜欢例如:我有这个 dict = {'24' : 3 ,'43' : 6} 对于 dict['80'] 它应该是 0 但对于 dict['-5'] 它应该是 1。有人可以帮忙吗

标签: pythoncollectionsdefaultdict

解决方案


不要使用defaultdict. 相反,子类UserDict

from collections import UserDict

class MyDict(UserDict):
    def __missing__(self, key):
        return 0 if int(key) > 0 else 1

d = MyDict({'24' : 3 ,'43' : 6})
print(d['24'])
print(d['80'])
print(d['-5'])

输出

3
0
1

推荐阅读