码迷,mamicode.com
首页 > 其他好文 > 详细

Day 6 Collections系列

时间:2016-07-24 18:00:31      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

counter:对字典进行处理,用于计算元素出现的个数

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wanghuafeng


import collections
#计数器,Counter
obj = collections.Counter("asdfghjgioccvbnjrtubvg6782bnsh2bn")
print(obj)
#取前4个数,排序按照从多到少
ret = obj.most_common(4)
print(ret)
#obj:处理完的数据
for k,v in obj.items():
print(k, v)

#elements:原生的值,未经过加工处理的
for i in obj.elements():
print(i)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wanghuafeng


import collections
obj = collections.Counter([‘11‘, ‘22‘, ‘33‘, ‘44‘, ‘55‘])
print(obj)
#增加
obj.update([‘eric‘, ‘11‘, ‘11‘])
print(obj)
#删除
obj.subtract([‘eric‘, ‘11‘, ‘11‘])
print(obj)

有序字典

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wanghuafeng


import collections
#列表+字典=有序字典,key取列表中的元素
dic = collections.OrderedDict()
dic[‘k1‘] = ‘v1‘
dic[‘k2‘] = ‘v2‘
dic[‘k3‘] = ‘v3‘
dic[‘k4‘] = ‘v4‘
dic[‘k5‘] = ‘v5‘
dic[‘k6‘] = ‘v6‘
dic[‘k7‘] = ‘v7‘
dic[‘k8‘] = ‘v8‘
print(dic)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wanghuafeng


import collections
#列表+字典=有序字典,key取列表中的元素
dic = collections.OrderedDict()
dic[‘k1‘] = ‘v1‘
dic[‘k2‘] = ‘v2‘
dic[‘k3‘] = ‘v3‘
dic[‘k4‘] = ‘v4‘
dic[‘k5‘] = ‘v5‘
dic[‘k6‘] = ‘v6‘
dic[‘k7‘] = ‘v7‘
dic[‘k8‘] = ‘v8‘
print(dic)
#移动到最后
dic.move_to_end(‘k1‘)
print(dic)
#后进先出
dic.popitem()
print(dic)
#指定取数,pop将取出的数据为己有
ret = dic.pop(‘k3‘)
print(dic)
print(ret)
#设置默认值,如果存在不做任何操作,如果不存在则增加
dic.setdefault(‘k9‘,‘22‘)
print(dic)
#更新
dic.update({‘k1‘:‘v1‘, ‘k10‘:‘v10‘})
print(dic)

默认字典

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wanghuafeng


import collections
values = [11, 22, 33, 44, 55, 66, 77, 88]
my_dict = collections.defaultdict(list)

for value in values:
if value > 33:
my_dict[‘k1‘].append(value)
else:
my_dict[‘k2‘].append(value)

print(my_dict)

可命名元祖

#创建类,defaultdict
MytupleClass = collections.namedtuple(‘MytupleClass‘,[‘x‘, ‘y‘, ‘z‘])
print(help(MytupleClass))
obj = MytupleClass(11, 22, 33)
print(obj.x)
print(obj.y)
print(obj.z)

双向队列

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wanghuafeng


import collections


d = collections.deque()
#增加一个
d.append(‘1‘)
#往左增加
d.appendleft(‘10‘)
d.appendleft(‘1‘)
print(d)
#统计个数
ret = d.count(‘1‘)
print(ret)
#扩展,右边增加
d.extend([‘yy‘, ‘qq‘, ‘11‘])
print(d)
#扩展,左边增加
d.extendleft([‘y1y‘, ‘q2q‘, ‘131‘])
print(d)
#从右取数插入左边
d.rotate(3)
print(d)

单向队列

import queue
#创建单向队列
q = queue.Queue()
#增加数据
q.put(‘123‘)
q.put(‘456‘)
print(q.qsize())
#按顺序取数据
print(q.get())
 

Day 6 Collections系列

标签:

原文地址:http://www.cnblogs.com/icsnow/p/5701132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!