class CmpValDict(dict):
""" dict subclass that stores values associated with each key based
on the return value of a function which allow the value passed to be
first compared to any already there (if there is no pre-existing
value, the second argument passed to the function will be None)
"""
def __init__(self, cmp=None, *args, **kwargs):
self.cmp = cmp if cmp else lambda nv,cv: nv # default returns new value
super(CmpValDict, self).__init__(*args, **kwargs)
def __setitem__(self, key, value):
super(CmpValDict, self).__setitem__(key, self.cmp(value, self.get(key)))
cvdict = CmpValDict(cmp=max)
cvdict['a'] = 43
cvdict['a'] = 17
print cvdict['a'] # 43
cvdict[43] = 'George Bush'
cvdict[43] = 'Al Gore'
print cvdict[43] # George Bush
不确定它是否“更整洁”,但避免重复的一种方法是使用面向对象的方法,并将内置的
dict
类的子类化,使某些东西能够做你想做的事情。这还有一个优点,即可以使用自定义类的实例来代替dict
实例,而无需更改其余代码。在只需为自己编写一个helper函数:
您可以使用封装该逻辑的update方法使values成为对象。或子类dictionary并修改
__setitem__
的行为。请记住,您这样做会使不熟悉您的代码的人不太清楚发生了什么。你现在所做的是非常明确和明确的。在相关问题 更多 >
编程相关推荐