您可以让Counter不写出“ Counter”吗? [英] Can you make Counter not write-out "Counter"?

查看:81
本文介绍了您可以让Counter不写出“ Counter”吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当我将计数器(从集合导入计数器中的)打印到文件时,我总是得到字面值 Counter({'Foo': 12})

So when I print the Counter (from collections import Counter) to a file I always get this the literal Counter ({'Foo': 12})

有没有办法使计数器不按字面意思写出来?因此它将改为写 {'Foo':12} 而不是 Counter({'Foo':12})

Is there anyway to make the counter not write out so literally? So it would instead write {'Foo' : 12} instead of Counter({'Foo' : 12}).

是的,但我很讨厌,但是以后我讨厌grep'n这个东西。

Yeah it's picky, but I am sick of grep'n the thing out of my files afterward.

推荐答案

您只需将 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的想法更好,但是:


I rather like JBernardo's idea better, though:

In [66]: import json

In [67]: counter
Out[67]: Counter({'Foo': 12})

In [68]: json.dumps(counter)
Out[68]: '{"Foo": 12}'

这样,您就不会失去计数器的特殊方法,例如 most_common ,并且在Python根据 Counter 构建字典时,您不需要额外的临时内存。

That way, you do not lose counter's special methods, like most_common, and you do not require extra temporary memory while Python builds a dict from a Counter.

这篇关于您可以让Counter不写出“ Counter”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆