定义与key
的{{1}}参数类似的自定义键函数的好方法是什么,用于list.sort
?
以下是一个示例用例:
collections.defaultdict
我想要的是告诉import collections
class Path(object):
def __init__(self, start, end, *other_features):
self._first = start
self._last = end
self._rest = other_features
def startpoint(self):
return self._first
def endpoint(self):
return self._last
# Maybe it has __eq__ and __hash__, maybe not
paths = [... a list of Path objects ...]
by_endpoint = collections.defaultdict(list)
for p in people:
by_last_name[p.endpoint()].append(p)
# do stuff that depends on lumping paths with the same endpoint together
使用by_endpoint
作为Path.endpoint
函数的方法,类似于key
的{{1}}参数,而不是必须将此关键定义放入key
类本身(通过list.sort
和Path
),因为同样支持"通过起点和#34;同样。
答案 0 :(得分:1)
这样的事情可能是:
from collections import defaultdict
class defaultkeydict(defaultdict):
def __init__(self, default_factory, key=lambda x: x, *args, **kwargs):
defaultdict.__init__(self, default_factory, *args, **kwargs)
self.key_func = key
def __getitem__(self, key):
return defaultdict.__getitem__(self, self.get_key(key))
def __setitem__(self, key, value):
defaultdict.__setitem__(self, self.get_key(key), value)
def get_key(self, key):
try:
return self.key_func(key)
except Exception:
return key
如果无法执行键功能,请注意回退到传入键的逻辑。这样你仍然可以使用字符串或任何键访问项目。
现在:
p = Path("Seattle", "Boston")
d = defaultkeydict(list, key=lambda x: x.endpoint())
d[p].append(p)
print(d) # defaultdict(<type 'list'>, {'Boston': [<__main__.Path object at ...>]})