您可以让Counter不写出“ Counter”吗?
问题内容:
因此,当我将Counter(from collections import Counter
)打印到文件中时,我总是得到字面值Counter ({'Foo': 12})
无论如何,有没有要使计数器不按字面意思写出来?因此它将改为写{'Foo' : 12}
而不是Counter({'Foo' : 12})
。
是的,这很挑剔,但我讨厌以后再把文件中的东西丢掉了。
问题答案:
您可以将传递Counter
给dict
:
counter = collections.Counter(...)
counter = dict(counter)
In [56]: import collections
In [57]: counter = collections.Counter(['Foo']*12)
In [58]: counter
Out[58]: Counter({'Foo': 12})
In [59]: counter = dict(counter)
In [60]: counter
Out[60]: {'Foo': 12}
不过,我更喜欢JBernardo的想法:
In [66]: import json
In [67]: counter
Out[67]: Counter({'Foo': 12})
In [68]: json.dumps(counter)
Out[68]: '{"Foo": 12}'
这样,您就不会丢失counter
的特殊方法,例如most_common
,并且在Python根据构造字典时不需要额外的临时内存Counter
。