格式化计数器的输出

18 python

我使用Counter来计算列表项的出现次数.我很难很好地展示它.对于以下代码,

category = Counter(category_list)
print category
Run Code Online (Sandbox Code Playgroud)

以下是输出,

Counter({'a': 8508, 'c': 345, 'w': 60})
Run Code Online (Sandbox Code Playgroud)

我必须如下显示上述结果,

a 8508
c 345
w 60
Run Code Online (Sandbox Code Playgroud)

我试图迭代计数器对象,但我没有成功.有没有办法很好地打印Counter操作的输出?

vau*_*tah 18

Counter本质上是一个字典,因此它有键和相应的值 - 就像普通字典一样.从文档:

Counter是用于计算可哈希对象的dict子类.它是一个无序集合,其中元素存储为字典键,其计数存储为字典值.

您可以使用此代码:

>>> category = Counter({'a': 8508, 'c': 345, 'w': 60})
>>> category.keys() 
dict_keys(['a', 'c', 'w'])
>>> for key, value in category.items():
...     print(key, value)
... 
a 8508
c 345
w 60
Run Code Online (Sandbox Code Playgroud)

但是,您不应该依赖字典中的键顺序.

Counter.most_common非常有用.引用我链接的文档:

返回n个最常见元素及其计数的列表,从最常见到最少.如果未指定n,则most_common()返回计数器中的所有元素.具有相同计数的元素是任意排序的.

(重点补充)

>>> category.most_common() 
[('a', 8508), ('c', 345), ('w', 60)]
>>> for value, count in category.most_common():
...     print(value, count)
...
a 8508
c 345
w 60
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 6

print调用类的__str__方法Counter,所以你需要覆盖它以获得打印操作的输出.

from collections import Counter
class MyCounter(Counter):
    def __str__(self):
        return "\n".join('{} {}'.format(k, v) for k, v in self.items())
Run Code Online (Sandbox Code Playgroud)

演示:

>>> c = MyCounter({'a': 8508, 'c': 345, 'w': 60})
>>> print c
a 8508
c 345
w 60
Run Code Online (Sandbox Code Playgroud)