collections工具库中的一些容器

1.defaultdict

#defaultdict解决使用dict最常见的问题,就是key为空的情况
#方法1:在每次get之前写一个if判断
if key in dict:
    return dict[key]
else:
    return None

data = [(1, 3), (2, 1), (1, 4), (2, 5), (3, 7)]
d = {}
for k, v in data:
    if k in d:
        d[k].append(v)
    else:
        d[k] = [v]
d

#方法2:用defaultdict
from collections import defaultdict
data = [(1, 3), (2, 1), (1, 4), (2, 5), (3, 7)]
d = defaultdict(list)
for k,v in data:
    d[k].append(v)
d    

2.Counter

#counter
words = ['apple', 'apple', 'pear', 'watermelon', 'pear', 'peach']
from collections import Counter
counter = Counter(words)
print(counter)

#要筛选topK
counter.most_common(2)

3.deque

#queue是队列,deque是双端队列
#deque常用api有append,pop,appendleft,popleft
from collections import deque
dque = deque(maxlen=10)
# 假设我们想要从文件当中获取最后10条数据
for i in f.read():
    dque.append(i)

4.namedtuple

#namedtuple
from collections import namedtuple
#这是个类
Student = namedtuple('Student',['name','score','age'])
#这是个实例
student = Student(name='xiaoming',score=99,age=20)
print(student.name)

#通过传入defaults参数来定义缺失值
#在Python的规范当中,必选参数一定在可选参数前面。所以nuamdtuple会自动右对齐
Student = namedtuple('Student', ['name', 'score', 'age'], defaults=(0, 0))

 

你可能感兴趣的:(python学习)