Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

python - Formatting output of Counter

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,

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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_common is very useful. Citing the documentation I linked:

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

(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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...