首页 > 技术文章 > python标准库之collections

dapan-no1 2019-04-16 00:06 原文

一.模块 collections 中的一个类—— OrderedDict 。
(字典让你能够将信息关联起来,但它们不记录你添加键 — 值对的顺序。要创建字典并记录其
中的键 — 值对的添加顺序,可使用模块 collections 中的 OrderedDict 类。 OrderedDict 实例的行为
几乎与字典相同,区别只在于记录了键 — 值对的添加顺序。)

from collections import OrderedDict
#假设age_1 到age_5 都存在(不写了)
my_dict=OrderedDict()
my_dict[age_1]="10"
my_dict[age_2]="20"
my_dict[age_3]="30"
my_dict[age_4]="40"
my_dict[age_5]="50"
for k,v in my_dict.items():
print("他们的顺序应该是:"+k+"对应"+v)


二.模块 collections 中的一个类—— deque。
deque类里有方法:
例子:d.append('x') 添加x到d的右端,不返回
d.appendleft('xx) 添加xx到d的左侧,不返回
d.clear() 清空
d.count(x) 统计x的个数
d.extend(可迭代的类型) 会把每个元素添加到d
d.index(x)返回x的索引,不存在的话报错
d.pop()删除右边的一个,没有就报错
d.remove(x) 去除x,不存在就报错
d.reverse()倒叙

rotate(n) 向右循环移动n,如果n是负数,就向左循环
例子:
d.rotate(1)
d
deque([1, 'a', 'd', 'f', 'g', 'h'])
>>> d.rotate(1)
>>> d
deque(['h', 1, 'a', 'd', 'f', 'g'])

 from collections import deque
 d=deque('abc')
 for i in d:
     print(i)


推荐阅读