2

因此,当我将 Counter ( from collections import Counter) 打印到文件时,我总是得到这个字面量Counter ({'Foo': 12})

有没有办法让计数器不按字面意思写出来?所以它会改为写{'Foo' : 12}而不是Counter({'Foo' : 12}).

是的,它很挑剔,但我厌倦了 grep'n 之后从我的文件中删除的东西。

4

4 回答 4

6

您可以将 to 传递Counterdict

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 从 构建 dict 时不需要额外的临时内存Counter

于 2013-04-19T00:24:07.053 回答
1

如何将其显式格式化为您想要的形式?

>>> import collections
>>> data = [1, 2, 3, 3, 2, 1, 1, 1, 10, 0]
>>> c = collections.Counter(data)
>>> '{' + ','.join("'{}':{}".format(k, v) for k, v in c.iteritems()) + '}'
"{'0':1,'1':4,'2':2,'3':2,'10':1}"
于 2013-04-19T00:28:34.943 回答
0

好吧,这不是很优雅,但是您可以简单地将其转换为字符串并切断前 8 个和最后 1 个字母:

x = Counter({'Foo': 12})
print str(x)[8:-1]
于 2013-04-19T00:23:46.843 回答
-1

您可以通过进入集合模块的源代码来更改计数器类的 __str__ 方法,但我不建议这样做,因为这会永久修改它。也许只是改变你打印的内容会更有益?

于 2013-04-19T00:25:53.853 回答