Introduction
Python provides us with 5 basic data structures: list, tuple, Dict, set, string;
Sometimes we need to maintain an orderly dict. So this time we are going to use the Python standard library to provide us with the collections package, it provides a number of useful collection classes, proficient in these collection classes, not only can let us write code more pythonic, but also can improve the efficiency of our program.
Defaultdict:
Defaultdict (default_factory) adds default_factory on top of the normal Dict (dictionary), which automatically generates the corresponding type of value when the key is absent,default_ The factory parameter can be specified as a list, set, int , and various legal types.
>>> from collections import defaultdict>>> s = [(' Red ', 1), (' Blue ', 2), (' Red ', 3), (' Blue ', 4), (' Red ') , 1), (' Blue ', 4)]
Example 1: Set Default_factory to List
We now have a list of the above (lists), although we have 6 sets of data, but after careful observation we find that we only have two color colors, but each color corresponds to multiple values. Now we want to convert this list to a dict (dictionary), and this Dict key (key) corresponds to a color,dict value (value) set to a list to hold multiple values corresponding to the color. We can use Defaultdict (list) to solve this problem.
# d can be seen as a dict (dictionary), Dict's value is a list (list) >>> d = defaultdict (lists) >>> for k,v in S: ... d[k].append (v). .. >>> ddefaultdict (<class ' list ', {' Blue ': [2, 4, 4], ' Red ': [1, 3, 1]})
Example 2: Setting Default_factory to set
There are some imperfections in the example above, such as {' Blue ': [2, 4, 4], ' Red ': [1, 3, 1]} The blue color in this defaultdict contains two 4,red colors containing two 1, but we do not want to contain duplicate elements, Consider using Defaultdict (set) to solve this problem at this time. The difference between a set (collection) and a list is that the same element is not allowed in set.
>>> d = defaultdict (set) >>> for k,v in S: ... d[k].add (v) ...>>> ddefaultdict (<class ' Set ' {' Blue ': {2, 4}, ' Red ': {1, 3}})
Example 3: Set default_factory to int
By using the form of defaultdict (int), we count the number of occurrences of each character in a string.
>>> s = ' Hello world ' >>> d = defaultdict (int) >>> for k in S: ... d[k] + = 1...>>> DD Efaultdict (<class ' int '), {' O ': 2, ' h ': 1, ' W ': 1, ' l ': 3, ': 1, ' d ': 1, ' E ': 1, ' R ': 1})
Ordereddict:
We know that the default dict (dictionary) is unordered, but in some cases we need to maintain dict order, this time can use Ordereddict, it is a subclass (subclass) of Dict, but on the basis of dict to maintain the dict of the orderly type, Let's take a look at how to use it.
>>> from collections import ordereddict# unordered dict>>> d = {' Banana ': 3, ' Apple ': 4, ' pear ': 1, ' Orange ': 2 }
Example 1: This is an unordered dict (dictionary), and now we can use ordereddict to make this dict orderly.
# to sort D by key >>> Ordereddict (sorted (D.items (), Key=lambda t:t[0]) ordereddict ([' Apple ', 4), (' Banana ', 3), (' Orange ', 2), (' Pear ', 1)] # will sort D by value >>> ordereddict (sorted (D.items (), Key=lambda t:t[1]) ordereddict ([(' Pear ', 1), (' Orange ', 2), (' Banana ', 3), (' Apple ', 4)]) # sort D by the length of the key >>> ordereddict (sorted (D.items (), key= Lambda T:len (t[0])) ordereddict ([' Pear ', 1), (' Apple ', 4), (' Orange ', 2), (' Banana ', 3)])
Example 2: Using the popitem (last=true) method allows us to delete the Key-value in the dict in the Order of LIFO (FIFO), that is, to delete the last inserted key-value pair, if Last=false follows the FIFO (first-in Delete Dict in Key-value.
>>> d = {' Banana ': 3, ' Apple ': 4, ' pear ': 1, ' orange ': 2}# sort D by key >>> D = ordereddict (sorted (D.items ( ), Key=lambda t:t[0])) >>> dordereddict ([' Apple ', 4), (' Banana ', 3), (' Orange ', 2), (' Pear ', 1)]) # Use the Popitem () method To remove the last Key-value pair >>> d.popitem (' pear ', 1) # Use Popitem (last=false) to remove the first key-value pair >>> D.popitem ( Last=false) (' Apple ', 4)
Example 3: Using move_to_end (key, Last=true) to change the key-value order of an ordered Ordereddict object, With this method we can insert any key-value of the sorted Ordereddict object into the beginning or end of the dictionary.
>>> d = Ordereddict.fromkeys (' ABCDE ') >>> dordereddict (' (' a ', none), (' B ', none), (' C ', none), (' d ', Non e), (' E ', none)] # Key-value The key to B to move to Dict's last >>> d.move_to_end (' B ') >>> dordereddict ([' A ', none), (' C ', none), (' d ', none), (' E ', none), (' B ', none)]) >>> '. Join (D.keys ()) ' Acdeb ' # moves the key-value of key B to the front of Dict >>> d.move_to_end (' B ', last=false) >>> '. Join (D.keys ()) ' BACDE '
Counter:
Example 1:counter is also a subclass of Dict, which is an unordered container that can be seen as a counter for counting the number of related elements that appear.
>>> from collections import counter>>> cnt = Counter () # Number of elements appearing in the statistics list >>> for word in [' Red ', ' bl UE ', ' red ', ' green ', ' blue ', ' Blue ']: ... cnt[word] + = 1...>>> cntcounter ({' Blue ': 3, ' Red ': 2, ' Green ': 1}) # Statistical word Number of elements appearing in string >>> cnt = Counter () >>> for ch in ' Hello ': ... cnt[ch] = cnt[ch] + 1...>>> Cntcount ER ({' l ': 2, ' O ': 1, ' H ': 1, ' E ': 1})
Example 2: Use the elements () method to return an iterator (iterator) based on the number of occurrences of an element, which is returned in any order, and ignored if the element count is less than 1.
>>> C = Counter (a=4, b=2, c=0, d=-2) >>> ccounter ({' A ': 4, ' B ': 2, ' C ': 0, ' d ':-2}) >>> C.elemen TS () <itertools.chain object at 0x7fb0a069ccf8>>>> Next (c) ' A ' # sort >>> sorted (c.elements ()) [' A ' , ' A ', ' a ', ' a ', ' B ', ' B ']
Example 3: Use Most_common (n) to return a list containing the top n elements of the Counter object in the list.
>>> C = Counter (' Abracadabra ') >>> ccounter ({' A ': 5, ' B ': 2, ' R ': 2, ' d ': 1, ' C ': 1}) >>> C.most_ Common (3) [(' A ', 5), (' B ', 2), (' R ', 2)]
Namedtuple:
Use Namedtuple (typename, Field_names) to name the elements in a tuple to make the program more readable.
>>> from collections import namedtuple>>> point = Namedtuple (' pointextension ', [' X ', ' y ']) >> > P = Point (1, 2) >>> p.__class__.__name__ ' pointextension ' >>> p.x1>>> p.y2
This article is from the "burning Years of Passion" blog, please be sure to keep this source http://liuzhengwei521.blog.51cto.com/4855442/1919825
The collections of the Python standard library