Collections is a python built-in collection module that provides a number of useful collection classes.
1.Counter Counter
Counter is a simple counter, for example, the number of statistical characters that appear:
>>> importcollections
>>> obj =collections. Counter (' Applebanana ')
>>> Print (obj)
Counter ({' A ': 4, ' n ': 2, ' P ': 2, ' E ': 1, ' l ': 1, ' B ': 1})
2.OrderedDict ordered dictionaries
When using Dict, key is unordered. We cannot determine the order of key when we iterate over the dict.
If you want to keep the key in order, you can use Ordereddict:
>>> od =collections. Ordereddict ()
>>> od[' K2 ']= ' K2 '
>>> od[' k1 '] = ' K1 '
>>> OD
Ordereddict ([' K2 ', ' K2 '), (' K1 ', ' K1 ')])
Or
>>> od =collections. Ordereddict ([' K2 ', ' V2 '), (' K1 ', ' v1 ')])
>>> OD
Ordereddict ([' K2 ', ' V2 '), (' K1 ', ' v1 ')])
3.defaultdict Default Dictionary
The default dictionary sets a default type for the value of the dictionary
Import Collections
Num =[11,22,33,44,55,66,77,88,99]
# to be My_dic the value of the dictionary is added by default List type
My_dic =collections.defaultdict (list)
For i in Num:
If I > 66:
my_dic[' K1 '].append (i)
Else
my_dic[' K2 '].append (i)
Print (My_dic)
4.namedtuple named Meta-ancestor
Namedtuple is a function that is used to create a custom tuple object, and set the tuple the number of elements and can be referenced using attributes rather than indexes tuple one of the elements.
in this way, we use Namedtuple It is easy to define a data type that has tuple invariant, and can be referenced according to the property, the use is very convenient
>>> Person = Collections.namedtuple (' pp ', [' name ', ' age '])
>>> p = person (' Apple ', 2)
>>> print (p.name)
>>> Print (P.age)
5.deque bidirectional queue
When using the list to store data, accessing the elements by index is fast, but inserting and deleting elements is slow because list is linear and the data is large, and insertions and deletions are inefficient.
Deque is a two-way list for efficient insert and delete operations, suitable for queues and stacks:
>>> dli =collections.deque ([+])
>>>dli.append (4)
>>> DLI
Deque ([1, 2, 3, 4])
>>>dli.appendleft (5) #appendleft向左插入数据
>>> DLI
Deque ([5, 1, 2, 3, 4])
This article is from the "Small New study Blog" blog, please be sure to keep this source http://oneserver.blog.51cto.com/4776118/1765466
Python Basics: Collections Module