【问题标题】:conditions on undefined keys in defaultdict [duplicate]defaultdict中未定义键的条件[重复]
【发布时间】:2019-08-19 18:36:13
【问题描述】:

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

【问题讨论】:

  • 如果你关心它们的数值,为什么键是字符串?

标签: python collections defaultdict


【解决方案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

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 2019-01-19
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2022-12-04
    相关资源
    最近更新 更多