Learn and test collections related methods:
#Coding=utf-8"""testcollections.py Practice and test the Collections collection Module"""ImportCollectionsImportUnitTestclasstestcollections (unittest. TestCase):deftest_namedtuple (self):"""Namedtuple is a function that creates a custom tuple object, specifies the number of tuple elements, and can refer to an element of a tuple using a property rather than an index. It is easy to define a data type with namedtuple, which has the invariant of tuple and can be referenced by attributes."""Job_type= Collections.namedtuple ('Job_type', ['H','M','L']) Job= Job_type ('High','in','Low') self.assertequal ('High', job. H) self.assertequal ('in', job. M) self.assertequal ('Low', job. L) Point= Collections.namedtuple (' Point', ['x','y']) P= Point () self.assertequal (1, p.x) self.assertequal (2, P.Y)defTest_deque (self):"""Deque is a two-way list for efficient insert and delete operations"""que= Collections.deque (['A', 1, 3,"B"]) #AddQue.append ("M") self.assertequal ("M", que[-1]) #Deleteres =Que.pop () self.assertequal ("M", Res)#add an element from the leftQue.appendleft ("L") self.assertequal ("L", que[0])#Remove from leftSelf.assertequal ("L", Que.popleft ())deftest_defaultdict (self):"""return default value when Defaultdict:key does not exist"""default_dict= Collections.defaultdict (Lambda:"N /A") default_dict['name'] ='Xiaoshitoutester'default_dict['Job'] ='Tester'Self.assertequal ('Xiaoshitoutester', default_dict['name']) self.assertequal ('Tester', default_dict['Job']) self.assertequal ('N /A', default_dict[' Age']) defTest_counter (self):"""Counter: Count the number of occurrences of a character"""Str_example="Xiaoshitoutester" #list_example = [' A22222 ', 1,3, ' B ']c =collections. Counter () forChinchStr_example:c[ch]+ = 1Self.assertequal (3, c['T'])if __name__=='__main__': Unittest.main ()
Python,collections Module