Python: collections--容器数据类型

collections--容器数据类型

Counter

Counter作为一个容器,可以跟踪相同的值增加了多少次。
Counter支持3种形式的初始化。调用Counter的构造函数时可以提供一个元素序列或者一个包含键和计数的字典,还可以使用关键字参数将字符串名映射到计数。

#! /usr/bin/env python
#coding=utf-8
import collections

print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
print collections.Counter({'a': 2, 'b': 3, 'c': 1})
print collections.Counter(a=2, b=3, c=1)

如果不提供任何参数,可以构造一个空的Counter,然后通过update()方法填充

#! /usr/bin/env python
#coding=utf-8
import collections

c = collections.Counter()
print 'Initial:', c

c.update('abcdaab')
print 'Sequence:', c

c.update({'a': 1, 'd': 5})
print 'Dict:', c

计值将根据新数据增加, 替换数据不会改变计数

访问计数

#! /usr/bin/env python
#coding=utf-8
import collections

c = collections.Counter('abcdaab')

for letter in 'abcde':
    print '%s : %d' %(letter, c[letter])

对于未知的元素,Counter不会产生KeyError。如果在输入中没有找到某个值,则其计数为0

elements()方法返回一个迭代器,将生成Counter知道的所有元素。

#! /usr/bin/env python
#coding=utf-8
import collections

c = collections.Counter('extremely')
c['z'] = 0
print c
print list(c.elements())

不能保证元素的顺序不变,另外计数小于或等于0的元素不包含在内。

使用most_common()可以生成一个序列,其中包含n个最常遇到的输入值及其对应计数。

#! /usr/bin/env python
#coding=utf-8
import collections

c = collections.Counter()

filepath = r'your real path'

with open(filepath, 'rt') as f:
    for line in f:
        c.update(line.rstrip().lower())
        
print 'Most common'
for letter, count in c.most_common(10):
    print '%s: %7d' % (letter, count)

Counter实例支持算术和集合操作来完成结果的聚集

#! /usr/bin/env python
#coding=utf-8
import collections

c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
c2 = collections.Counter('alphabet')

print "C1:", c1
print "C2:", c2

print "\nCombined counts:"
print c1 + c2

print '\nSunstraction'
print c1 - c2

print '\nIntersection (taking positive minumums)'
print c1 & c2

print '\nUnion (taking maximums)'
print c1 | c2

每次通过一个操作生成一个新的Counter时,计数为0或负数的元素都会被删除。

defaultdict
标准字典包括一个方法setdefault()来获取一个值,如果这个值不存在则建立一个默认值。与之相反,defaultdict初始化容器时会让调用者提前指定默认值。

#! /usr/bin/env python
#coding=utf-8
import collections

def default_factory():
    return 'default value'

d = collections.defaultdict(default_factory, foo='bar')
print 'd', d
print 'foo ==>', d['foo']
print 'bar ==>', d['bar']
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,264评论 19 139
  • http://python.jobbole.com/85231/ 关于专业技能写完项目接着写写一名3年工作经验的J...
    燕京博士阅读 12,246评论 1 118
  • 原文链接:http://www.startup-partner.com/2006.html 政策红利就是创业风口,...
    思达派阅读 1,216评论 0 0
  • 这是一条热闹的巷子 有着甜腻的糖果和好吃的水果 在巷子深处召唤 我最爱的葡萄架子 也在那里 还有那轻摇的蒲扇 以及...
    青正堂主阅读 1,382评论 0 3
  • 2017.8.19不知不觉亲子阅读打卡计划已经坚持到了47天了,阅读容易坚持不易,打卡容易坚持也不易!想想坚持下去...
    博古茹今阅读 1,450评论 0 0

友情链接更多精彩内容