一. namedtuple命名元组
from collections import namedtuple
Student=namedtuple('student','name age')
Tom=Student('tom',20)
Jerry=Student('jerry',18)
print(1,Tom.name)
print(2,Jerry.name)
print(3,type(Jerry))
运行结果:
1 tom
2 jerry
3 <class '__main__.student'>
from collections import namedtuple
Point=namedtuple('p','x,y')
print(0,type(Point))
p1=Point(4,5)
print(1,p1)
print(2,p1.x)
print(3,p1.y)
print(4,p1.x+p1.y)
运行结果:
0 <class 'type'>
1 p(x=4, y=5)
2 4
3 5
4 9
二. defaultdict默认字典
传统:
d1 = {}
for k in "abcde":
for v in range(5):
if k not in d1.keys():
d1[k] = []
d1[k].append(v)
print(d1)
print(type(d1))
运行结果:
{'d': [0, 1, 2, 3, 4], 'c': [0, 1, 2, 3, 4], 'a': [0, 1, 2, 3, 4], 'b': [0, 1, 2, 3, 4], 'e': [0, 1, 2, 3, 4]}
<class 'dict'>
演化:
from collections import defaultdict
d2 = defaultdict(list)
for k in "mnopq":
for v in range(3):
d2[k].append(v)
print(d2)
print(type(d2))
运行结果:
defaultdict(<class 'list'>, {'o': [0, 1, 2], 'p': [0, 1, 2], 'm': [0, 1, 2], 'n': [0, 1, 2], 'q': [0, 1, 2]})
<class 'collections.defaultdict'>
三. OrderedDict有序字典
from collections import OrderedDict
import random
d = {'banana':3,'apple':4,'pear':1,'orange':2}
print(1,d)
keys = list(d.keys())
random.shuffle(keys)
print(2,keys)
od = OrderedDict()
for key in keys:
od[key] = d[key]
print(3,od)
运行结果:
1 {'orange': 2, 'banana': 3, 'pear': 1, 'apple': 4}
2 ['orange', 'pear', 'banana', 'apple']
3 OrderedDict([('orange', 2), ('pear', 1), ('banana', 3), ('apple', 4)])