Python 计数器的格式化输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20316299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:10:37  来源:igfitidea点击:

Formatting output of Counter

python

提问by

I have used Counter to count the number of occurrence of the list items. I have trouble in displaying it nicely. For the below code,

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

category = Counter(category_list)
print category

the following is the output,

以下是输出,

Counter({'a': 8508, 'c': 345, 'w': 60})

I have to display the above result as follows,

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

a 8508
c 345
w 60

I tried to iterate over the counter object but I'm unsuccessful. Is there a way to print the output of the Counter operation nicely?

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

采纳答案by vaultah

Counteris essentially a dictionary, thus it has keys and corresponding values - just like the ordinary dictionary. From the documentation:

Counter本质上是一个字典,因此它有键和对应的值——就像普通的字典一样。从文档

A Counter is a dictsubclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

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

You can use this code:

您可以使用此代码:

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

However, you shouldn't rely on the order of keys in dictionaries.

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

Counter.most_commonis very useful. Citing the documentation I linked:

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

Return a list of the n most common elements and their counts from the most common to the least. If nis not specified, most_common()returns all elements in the counter. Elements with equal counts are ordered arbitrarily.

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

(emphasis added)

(强调)

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

回答by

This works:

这有效:

>>> from collections import Counter
>>> counter = Counter({'a': 8508, 'c': 345, 'w': 60})
>>> for key,value in sorted(counter.iteritems()):
...     print key, value
...
a 8508
c 345
w 60
>>>

Here is a reference on sortedand one on dict.iteritems.

这里是一个参考sorted和一个dict.iteritems

回答by Ashwini Chaudhary

printcalls __str__method of Counterclass, so you need to override that in order to get that output for print operation.

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())

Demo:

演示:

>>> c = MyCounter({'a': 8508, 'c': 345, 'w': 60})
>>> print c
a 8508
c 345
w 60

回答by wirthra

If you do not care abut having brackets at the beginning and the end another option is using pprint. It sorts the counter alphabetically for you.

如果您不关心开头和结尾是否有括号,则另一个选项是使用pprint。它为您按字母顺序对计数器进行排序。

import pprint
from collections import Counter

category = Counter({'a': 8508, 'c': 345, 'w': 60})
pprint.pprint(dict(category),width=1)

Output:

输出:

{'a': 8508,
 'c': 345,
 'w': 60}