drootang答案的另一种解决方案是使用自定义类:
from collections import defaultdict, Counter
class NamedCounter:
def __init__(self, name = '', counter = None):
self.counter = counter if counter else Counter()
self.name = name
def __repr__(self):
return 'NamedCounter(name={}, counter={})'.format(
repr(self.name), repr(self.counter))
d = defaultdict(NamedCounter)
d['x'].counter['b'] += 1
d['x'].counter['b'] += 1
d['x'].name = 'X counter'
print(d)
defaultdict(<class __main__.NamedCounter at 0x19de808>, {'x': NamedCounter(name='X counter', counter=Counter({'b': 2}))})
或者,您可以扩展Counter
以将名称合并到计数器本身中:
from collections import defaultdict, Counter
class NamedCounter(Counter):
def __init__(self, name = '', dict = None):
super(Counter, self).__init__(dict if dict else {})
self.name = name
def __repr__(self):
return 'NamedCounter(name={}, dict={})'.format(
repr(self.name), super(Counter, self).__repr__())
d = defaultdict(NamedCounter)
d['x']['b'] += 1
d['x']['b'] += 1
d['x'].name = 'X counter'
print(d)
defaultdict(<class '__main__.NamedCounter'>, {'x': NamedCounter(name='X counter', dict={'b': 2})})