collections主要有以下几个数据类型
- namedtuple:对tuple各个部分进行命名
- deque:双端队列
- Counter:计数器
- OrderedDict: 有序的字典
- defaultdict:带有默认值的字典
namedtuple
对tuple中的各个元素设定名称,并可以利用名称来访问
from collections import namedtuple, deque, defaultdict, OrderedDict
d = (1, 185, 20)
Person = namedtuple('Person', ['sex', 'tall', 'age'])
dd = Person(1, 198, 23)
print(dd)
print(dd.sex)
Output:
Person(sex=1, tall=198, age=23)
1
[Finished in 0.1s]
deque
list的插入和取出是O(n),而deque是O(1),快很多
from collections import namedtuple, deque, defaultdict, OrderedDict
q = deque([1, 2, 3])
print(q)
# 尾部插入和删除
q.append(4)
print(q)
q.pop()
print(q)
# 头部插入和删除
q.appendleft(0)
print(q)
q.popleft()
print(q)
Output:
deque([1, 2, 3])
deque([1, 2, 3, 4])
deque([1, 2, 3])
deque([0, 1, 2, 3])
deque([1, 2, 3])
[Finished in 0.1s]
Counter
统计字数
from collections import namedtuple, deque, defaultdict, OrderedDict,Counter
s = ' im happy'
re = Counter(s)
print(re)
print(re.most_common(2))
Output:
Counter({'p': 2, ' ': 2, 'h': 1, 'm': 1, 'a': 1, 'y': 1, 'i': 1})
[('p', 2), (' ', 2)]
[Finished in 0.1s]
OrderedDict
Python自带的字典是无序的,当需要有序字典时。。
from collections import namedtuple, deque, defaultdict, OrderedDict,Counter
a = (
('A', 1),
('B', 2),
('C', 3)
)
print(type(a))
b = dict(a)
# 注意这里的b输出顺序不是a的顺序
print(type(b))
print(b)
# 注意这里c的输出顺序与a相同
c = OrderedDict(a)
print(type(c))
print(c)
Output:
<class 'tuple'>
<class 'dict'>
{'A': 1, 'C': 3, 'B': 2}
<class 'collections.OrderedDict'>
OrderedDict([('A', 1), ('B', 2), ('C', 3)])
[Finished in 0.1s]
defaultdict
原生dict若使用dict[key]形式访问时,若指定的key不存在时,抛出KeyError错误
defaultdict中若指定key不存在,则抛出默认值:[]
from collections import namedtuple, deque, defaultdict, OrderedDict,Counter
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
d[k].append(v)
print(d)
print(d['blue'])
print(d['white']) # white不存在,返回[]
print(d) #此时已经将'white': [] 加入到字典
Output:
defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})
[2, 4]
[]
defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'white': [], 'red': [1]})
[Finished in 0.1s]
网友评论