python - defaultdict 中未定义键的条件
问题描述
我是 python 新手,我想在其中的集合模块中使用 defaultdict 编写代码,如下所示: defaultdict (lambda:'0') 但我只希望那些未定义键的值为 0,其中键大于 0 喜欢例如:我有这个 dict = {'24' : 3 ,'43' : 6} 对于 dict['80'] 它应该是 0 但对于 dict['-5'] 它应该是 1。有人可以帮忙吗
解决方案
不要使用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
推荐阅读
- cmake - 链接不适用于`add_subdirectory`
- android - 从android中适配器类的内部存储中删除文件
- laravel - 获取聊天对话的所有用户
- c - 为什么即使将 curl 库作为头文件包含在内,我们还要链接它?
- flutter - 如何在颤动的表格中制作可扩展的行?
- unity3d - 修改 Android 应用程序
- laravel - Laravel Eloquent 中两个表的连接结果错误?
- github-actions - GitHub Actions 工作
- python - 任何py文件都可以称为模块吗?
- python - 如何将变量和 UOM 插入为 ManyToManyField