Basic introduction of Collections Module
As we all know, Python has some built-in data types, such as str, int, list, tuple, dict, and so on, the collections module provides several additional data types based on these built-in data types:
1.namedtuple (): Generates a tuple subclass that can use a name to access element content
2.deque: Two-terminal queue, which can quickly append and eject objects from the other side
3.Counter: Counter, mainly used to count
4.OrderedDict: Ordered Dictionary
5.defaultdict: A dictionary with default values
Namedtuple ()
Namedtuple is primarily used to produce data objects that can use names to access elements, and is typically used to enhance the readability of the code, especially when accessing some tuple types of data.
Give me a chestnut.
Copy Code code as follows:
#-*-Coding:utf-8-*-
"""
For example, our users have one such data structure, each object is a tuple with three elements.
Using the Namedtuple method makes it easy to generate more readable and better data structures through tuple.
"""
From collections Import Namedtuple
Websites = [
(' Sohu ', ' http://www.google.com/', U ' Charles Zhang '),
(' Sina ', ' http://www.sina.com.cn/', U ' leverling '),
(' 163 ', ' http://www.163.com/', U ' ding lei ')
]
Website = namedtuple (' Website ', [' name ', ' url ', ' founder '])
For website in websites:
Website = website._make (website)
Print website
# Result:
Website (name= ' Sohu ', url= ' http://www.google.com/', founder=u ' \u5f20\u671d\u9633 ')
Website (name= ' Sina ', url= ' http://www.sina.com.cn/', founder=u ' \u738b\u5fd7\u4e1c ')
Website (name= ' 163 ', url= ' http://www.163.com/', founder=u ' \u4e01\u78ca ')
Deque
Deque is actually the abbreviation of double-ended queue, translation is a two-terminal queue, its biggest benefit is to achieve a rapid increase from the queue head and remove objects:. Popleft (),. Appendleft ().
You might say that the native list can also add and remove objects from the head? Just like this:
Copy Code code as follows:
L.insert (0, V)
L.pop (0)
It is worth noting, however, that the time complexity of these two usages of the list object is O (n), which means that as the number of elements increases it is time-consuming to increase linearly. The use of Deque objects is O (1) complexity, so when your code has such a requirement, be sure to remember to use deque.
As a two-terminal queue, Deque also offers a number of other handy methods, such as rotate.
Give me a chestnut.
Copy Code code as follows:
#-*-Coding:utf-8-*-
"""
Here's an interesting example of using the Deque rotate method to implement an infinite loop
The Load animation
"""
Import Sys
Import time
From collections Import Deque
fancy_loading = Deque (' >--------------------')
While True:
print ' \r%s '% '. Join (fancy_loading),
Fancy_loading.rotate (1)
Sys.stdout.flush ()
Time.sleep (0.08)
# Result:
# an endless cycle of racing lights
------------->-------
Counter
The counter is a very commonly used functional requirement, and collections also provides you with this function.
Give me a chestnut.
Copy Code code as follows:
#-*-Coding:utf-8-*-
"""
The following example uses the Counter module to count the occurrences of all characters in a sentence
"""
From collections Import Counter
s = ' ' A Counter is a dict subclass for counting hashable objects. It is a unordered collection where elements are stored as dictionary keys and their counts are as stored value S. Counts are allowed to is any integer value including zero or negative Counts. The Counter class is similar to bags or multisets into other languages. Lower ()
c = Counter (s)
# gets the 5 characters that appear most frequently
Print C.most_common (5)
# Result:
[(', Si], (' E ', M, (' s '), (' A ', '), (' t ', 24)]
Ordereddict
In Python, dict this data structure because of the hash characteristics, is unordered, which in some cases brings us some trouble, fortunately, the collections module provides us with the ordereddict, when you want to get an orderly Dictionary object, use it right.
Give me a chestnut.
Copy Code code as follows:
#-*-Coding:utf-8-*-
From collections Import Ordereddict
Items = (
(' A ', 1),
(' B ', 2),
(' C ', 3)
)
Regular_dict = dict (items)
Ordered_dict = ordereddict (items)
print ' Regular Dict: '
For K, v. in Regular_dict.items ():
Print K, V
print ' Ordered Dict: '
For K, v. in Ordered_dict.items ():
Print K, V
# Result:
Regular Dict:
A 1
C 3
B 2
Ordered Dict:
A 1
B 2
C 3
Defaultdict
As we all know, when using the Python native data structure dict, if you access it in such a way as D[key], a Keyerror exception is thrown when the specified key does not exist.
However, if you use Defaultdict, as long as you pass in a default factory method and then request a nonexistent key, the factory method is invoked to use its result as the default value for this key.
Copy Code code as follows:
#-*-Coding:utf-8-*-
From collections Import Defaultdict
Members = [
# Age, Name
[' Male ', ' John '],
[' Male ', ' Jack '],
[' Female ', ' Lily '],
[' Male ', ' Pony '],
[' Female ', ' Lucy '],
]
result = Defaultdict (list)
For sex, name in:
Result[sex].append (name)
Print result
# Result:
Defaultdict (<type ' list ', {' Male ': [' John ', ' Jack ', ' Pony '], ' female ': [' Lily ', ' Lucy ']})
Resources
The above is just very simple to introduce the main content of the collections module, the main purpose is when you encounter a suitable place to use them, can remember and use them, play a multiplier effect.
If you want to have a more comprehensive and in-depth understanding of them, it is recommended to read the official document and module source code.
Https://docs.python.org/2/library/collections.html#module-collections