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

南笙酒味 提交于 2019-12-01 10:32:19

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.

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

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]

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?

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