python – DefaultDict的替代品
发布时间:2020-12-20 12:02:13 所属栏目:Python 来源:网络整理
导读:不幸的是,对我来说,我需要使脚本向后兼容w / Python 2.4,并且2.4版本中不存在defaultdict. 什么可以替代呢? 给定键的数据结构是以下列表: [{'red': (12,1,12),'white': (30,2,60),'blue': (8,4),'orange': (9,4,8),'black': (10,12,4)}] 编辑: 添加使用信
不幸的是,对我来说,我需要使脚本向后兼容w /
Python 2.4,并且2.4版本中不存在defaultdict.
什么可以替代呢? 给定键的数据结构是以下列表: [{'red': (12,1,12),'white': (30,2,60),'blue': (8,4),'orange': (9,4,8),'black': (10,12,4)}] 编辑: defDict[key1].append(... ...) 然后它传递给密钥的几种方法:val(列表)查找和密钥删除. 特别是删除: if len(defDict[key1][0]) == 0: del defDict[key1] 编辑:NoneType上的错误 print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" print defDict[key] print "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" if len(defDict[key][0]) == 0: #del defDict[key] 错误: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx None yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy if len(defDict[key][0]) == 0: TypeError: 'NoneType' object has no attribute '__getitem__' 我认为错误来自关键: print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" print defDict[key] print "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" 输出: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx None yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 解决方法
您可以以非常简单的方式实现自己的defaultdict.
def defaultdict(default_type): class DefaultDict(dict): def __getitem__(self,key): if key not in self: dict.__setitem__(self,key,default_type()) return dict.__getitem__(self,key) return DefaultDict() list_dict = defaultdict(list) list_dict['a'].append(1) print list_dict # {'a': [1]} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |