码迷,mamicode.com
首页 > 编程语言 > 详细

Python collections类

时间:2016-04-30 14:16:18      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

c = Counter(‘abcdeabcdabcaba‘) 
import collections
c = collections.Counter(‘abcdeabcdabcaba‘)
print (c)
结果:Counter({‘a‘: 5, ‘b‘: 4, ‘c‘: 3, ‘d‘: 2, ‘e‘: 1})
结论:统计字符串出现的次数


import collections
c = collections.Counter(‘abcdeabcdabcaba‘)
print (c)

ret = c.most_common(2)
print (ret)
结果:[(‘a‘, 5), (‘b‘, 4)]
结论:统计出现次数最多的两个字符串

import collections
c = collections.Counter(‘abcdeabcdabcaba‘)
print (c)
print (sorted(c))
结果:[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]
结论:列出所有唯一的元素

import collections
c = collections.Counter(‘abcdeabcdabcaba‘)
print (c)
for k,v in c.items():
print (k,v)
结果:

 Counter({‘a‘: 5, ‘b‘: 4, ‘c‘: 3, ‘d‘: 2, ‘e‘: 1})
 a 5
 c 3
 e 1
 d 2
 b 4

 结论:统计各个字符串出现的次数

 

OrderedDict

 

import collections
dic = collections.OrderedDict()
dic[‘k3‘] = ‘v3‘
dic[‘k1‘] = ‘v1‘
dic[‘k2‘] = ‘v2‘
print (dic)
结果:OrderedDict([(‘k3‘, ‘v3‘), (‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘)])
结论:用列表来维系有序字典

defaultdict
import collections
values = [11,22,33,44,55,66,77,88,99]
dic = collections.defaultdict(list) #设置缺省为list类型
for value in values:
if value <66:
dic[‘k1‘].append(value)
else:
dic[‘k2‘].append(value)
print (dic[‘k1‘])
print (dic[‘k2‘])

不使用缺省字典
values = [11,22,33,44,55,66,77,88,99]
dic1 = {‘k1‘:[]}
dic2 = {‘k2‘:[]}

for value in values:
if value < 66:
dic1[‘k1‘].append(value)
else:
dic2[‘k2‘].append(value)
print (dic1)
print (dic2)
结果:

  {‘k1‘: [11, 22, 33, 44, 55]}
  {‘k2‘: [66, 77, 88, 99]}

 结论:必须制定dic1,dic2的值为list空表

  namedtuple(可命名的元祖)

import collections

Test = collections.namedtuple(‘Test‘,(‘x‘,‘y‘,‘z‘))
obj = Test(11,22,33)
print (obj.x)
结果:11
结论:针对元祖,要访问数据只能通过下标来访问,但是对于可命名的元祖,可以通过构建新的一个类(譬如Test),然后调用方法来实现

 双向队列

import collections
dq = collections.deque()

单向队列
import queue
q = queue.Queue()
q.put("123")
r = q.get()
print (r)


 

 

 



Python collections类

标签:

原文地址:http://www.cnblogs.com/python-study/p/5447939.html

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