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

后端 未结 4 1715
渐次进展
渐次进展 2021-01-15 13:22

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

Is there anyw

相关标签:
4条回答
  • 2021-01-15 13:27

    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?

    0 讨论(0)
  • 2021-01-15 13:42

    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]
    
    0 讨论(0)
  • 2021-01-15 13:47

    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}"
    
    0 讨论(0)
  • 2021-01-15 13:48

    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.

    0 讨论(0)
提交回复
热议问题