Can you make Counter not write-out “Counter”?

青春壹個敷衍的年華 提交于 2019-12-01 08:40:53

问题


So when I print the Counter (from collections import Counter) to a file I always get this the literal 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}).

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


回答1:


You could just pass the Counter to 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}

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}'

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.




回答2:


What about explicitly formatting it into the form that you want?

>>> 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}"



回答3:


Well this isn't very elegant, but you can simply cast it as a string and cut off the first 8 and last 1 letters:

x = Counter({'Foo': 12})
print str(x)[8:-1]



回答4:


You could change the __str__ method of the counter class by going into the source code for the collections module, but I wouldn't suggest that as that permanently modifies it. Maybe just changing what you print would be more beneficial?



来源:https://stackoverflow.com/questions/16095220/can-you-make-counter-not-write-out-counter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!