3.14 collections模块

1.namedtuple: 生成可以使用名字来访问元素内容的tuple

from collections import namedtuple
point = namedtuple('Point',['x','y'])
print(type(point))
p = point(1,2)
print(p)#Point(x=1, y=2)
print(p[0])#1
print(p.x)#1
struct_time = namedtuple('struct_time',['tm_year', 'tm_mon', 'tm_mday'])
st = struct_time(2019,7,3)
print(st)#struct_time(tm_year=2019, tm_mon=7, tm_mday=3)

2.deque: 类似于列表的一种容器型数据,插入元素删除元素效率高.

from collections import deque
q = deque(['a',1,'c','d'])
print(q)#deque(['a', 1, 'c', 'd'])
q.append('e')
q.appendleft('ly')#从左边添加
q.appendleft('dfs')
print(q)#deque(['dfs', 'ly', 'a', 1, 'c', 'd', 'e'])
q.pop()#删除最后一个
q.popleft()#删除最左边的元素
print(q)

按照索引取值
print(q[0])
按照索引删除任意值
del q[2]
print(q)
q.insert(1,'2')
print(q)

3.OrderedDict: 有序字典

d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d)
from collections import OrderedDict
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od['a'])
print(od['b'])
返回结果:
{'a': 1, 'b': 2, 'c': 3}
1
2

4.defaultdict: 带有默认值的字典

默认值字典
l1 = [11, 22, 33, 44, 55, 77, 88, 99]
dic = {}
for i in l1:
	if i<66:
		if 'key1'not in dic:
			dic['key1'] = []
		dic['key1'].append(i)
	else:
		if 'key2'not in dic:
			dic['key2'] = []
		dic['key2'].append(i)
print(dic){'key1': [11, 22, 33, 44, 55], 'key2': [77, 88, 99]}
from collections import defaultdict
l1 = [11, 22, 33, 44, 55, 77, 88, 99]
dic = defaultdict(list)
for i in l1:
	if i < 66:
		dic['key1'].append(i)
	else:
		dic['key2'].append(i)
print(dict(dic))
{'key1': [11, 22, 33, 44, 55], 'key2': [77, 88, 99]}
dic = defaultdict(lambda :None)
# dic = defaultdict(None)
for i in range(1,4):
    dic[i]
print(dic)

5..Counter: 计数器,主要用来计数

c = Counter('flkjdasffdfakjsfdsaklfdsalf')  # 计数器
print(c)
print(c['f'])
返回结果:
Counter({'f': 7, 'd': 4, 'a': 4, 's': 4, 'l': 3, 'k': 3, 'j': 2})
7
posted @ 2019-07-21 14:34  God_with_us  阅读(112)  评论(0编辑  收藏  举报