Python contains a number of standard programming data structures, such as list (lists), tuple (tuples), dict (dictionaries), and set (), which can be derived from a built-in type for customization if the existing data types do not meet the requirements. Or, use an abstract base class defined in collections as a starting point to build a new container type.
The collections module contains container data types other than the built-in list,dict,tuple. Counter as a container, you can track how many times the same value has been added. This class can be used to implement algorithms for bag and multiset data structures commonly used in other languages.
Initialization
counter supports three forms of initialization, where the counter constructor provides a sequence of elements or a dictionary containing keys and counts, and also uses keyword parameters to map string names to counts.
Simple demo:
#coding =utf-8
Import Collections
str1=[' A ', ' B ', ' C ', ' d ', ' a ', ' a ', ' B ', ' C ']
m=collections. Counter (str1)
print str1 print
m
print m[' a '] #字符a出现的次数
print m[' B '] #字符b出现的次数
Results:
Select an English text below and count the number of occurrences of the word, returning the number of occurrences of a word
What a python line of code can accomplish, don't use two lines
#coding =utf-8
Import Collections
import OS with
open (' Str.txt ') as File1: #打开文本文件
str1=file1.read (). Split (') #将文章按照空格划分开
Print original text: \ n%s "% str1
print" \ n the number of occurrences of each word: \ n%s "% collections. Counter (str1)
print collections. Counter (STR1) [' was '] #以字典的形式存储, the key value for each character is the number of times it appears in the text
Results:
Short code, very easy to understand, a look at it.