Python9-module1-day19
In addition to the built-in data types (dict, list, set, tuple), the collections module also provides several additional data types: Counter, deque, defaultdict, namedtuple, and OrderedDict, etc.
1.namedtuple: Generate a tuple that can access element content by name
2.deque: Double-ended queue, which can quickly append and push objects from the other side
3.Counter: Counter, mainly used to count
4.OrderedDict: Ordered dictionary
5. defaultdict: a dictionary with default values
namedtuple
from collections import namedtuple Point = namedtuple('point',['x','y','z']) p1 = Point(3,2,1) p2 = Point(1,2,3) print(p1.x) print(p1.y) print(p1) print(p2.x) print(p2.y) print(p2)
Card = namedtuple('card',['suits','number']) c1 = Card('红心',2) print(c1) print(c1.number) print(c1.suits)
about
from collections import deque dq = and ([1,2 ]) dq .append( ' a ' ) #Put the data from the back [1,2,'a'] dq .appendleft( ' b ' ) #Put the data from the front ['b',1,2,'a'] dq. insert(2,3) # ['b',1,3,2,'a'] print (dq.pop()) #Get data from the back print (dq .popleft()) #Get data from the front a b
# OrderedDict
from collections import OrderedDict d = dict([( ' a ' , 1), ( ' b ' , 2), ( ' c ' , 3 )]) # dict's Key is unordered {'a': 1, 'c': 3 , 'b': 2} od = OrderedDict([( ' a ' , 1), ( ' b ' , 2), ( ' c ' , 3 )]) print (od) # OrderedDict's Key is an ordered OrderedDict ([( ' a ' , 1), ( ' b ' , 2), ( ' c ' ,3)])
# defaultdict
from collections import defaultdict values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = defaultdict(list) for value in values: if value>66: my_dict['k1'].append(value) else: my_dict['k2'].append(value)
When used , if the referenced Key does not exist, it will be thrown . If you want to return a default value when the key does not exist, you can use :dict
KeyError
defaultdict
>>> from collections import defaultdict >>> dd = defaultdict( lambda : ' N/A ' ) >>> dd[ ' key1 ' ] = ' abc ' >>> dd[ ' key1 ' ] # key1 exists ' abc ' >>> dd[ ' key2 ' ] # key2 does not exist, return the default value ' N/A '