namedtuple generation can use the name to access the content of the element tuple
from collections import namedtuple
namedtuple(
typename: str, field_names: Union[str, Iterable[str]],
verbose: bool = ..., rename: bool = ...
)
namedtuple (name, attributes)
from collections import namedtuple Point = namedtuple('point',['x','y','z']) p = Point(1,2,3) print(p.x) print(p.y) print(p) # 1 # 2 # point(x=1, y=2, z=3)
Card = namedtuple('card',['suits','number']) c1 = Card('红桃',3) print(c1) print(c1.number) print(c1.suits) # card(suits='红桃', number=3) # 3 # 红桃
deque deque, from the other side can be quickly and additional objects Release
queue
import queue
q = queue.Queue()
q.put(10)
q.put(5)
print(q.qsize())
print(q.get())
from Collections Import the deque DQ = the deque ([1,2 ]) dq.append ( ' A ' ) # reproducing data from behind dq.appendleft ( ' B ' ) # front discharge data dq.insert (l, 3 ) Print ( dq.pop ()) # fetch data from the back Print (dq.popleft ()) # front access to data # A # B
Counter counter for counting the main
from collections import Counter
c = Counter('sahdqiuopweedwiuyq')
print(c)
Counter({'d': 2, 'q': 2, 'i': 2, 'u': 2, 'w': 2, 'e': 2,
's': 1, 'a': 1, 'h': 1, 'o': 1, 'p': 1, 'y': 1})
OrderedDict ordered dictionary
When using dict, Key is disordered, when the iterative dict do not determine the order of Key
If you want to keep the order Key, you can use OrderedDict:
from collections import OrderedDict od = OrderedDict([('a',1),('b',2),('c',3)]) print(od) print(od['a']) d = dict([('a',1),('b',2),('c',3)]) print(d) OrderedDict([('a', 1), ('b', 2), ('c', 3)]) 1 {'a': 1, 'b': 2, 'c': 3}
Dictionary defaultdict with default values
from collections import defaultdict value = [11,22,33,44,55,66,77,88,99,90] my_dic = defaultdict(list) for i in value: if i>66: my_dic['k1'].append(i) else: my_dic['k2'].append(i) print(my_dic)#defaultdict(<class 'list'>, {'k2': [11, 22, )33, 44, 55, 66], 'k1': [77, 88, 99, 90]} d = defaultdict(lambda :5) print(d['k'])#5