collections求和方法_collections——高性能容器数据类型

由于最近对机器学习算法感兴趣,一直知道python有一个包collections封装了一些比dict,list之类高级点的类,所以抽空研究下,为接下来的工作准备。

主要参考是https://docs.python.org/2/library/collections.html#defaultdict-objects官方的文档,根据不高的英文水平翻译和理解总结出来的,如果有错误欢迎提醒,万一,您有兴趣转载的也请注明是@瓜棚

collections封装的结构主要有5个:

###########################################################################################################################################

Counter * 字典(dict)的子类用来统计可哈希对象的值 * new in py 2.7 *deque* 双端队列,两端都可以作为队列的结束,方便前端插入需求 * new in py 2.4 *namedtuple* tuple的子类,可以用于按名字标识元组 * new in py 2.6 *OrderedDict* dict的子类,创建一个可哈希的有序字典 * new in py 2.7 *defaultdict* dict的子类,当某个key不存在时,一共一个默认值,而不是报KeyError * new in py 2.5 *

Counter类

example:

from collections importCounter

cnt=Counter()for word in ['1','2','3','1','2','1']:

cnt[word]+=1cnt#Counter({'1':3,'2':2,'3':1})######################################统计一段话里出现次数最多的10个词和各自的次数

text = ['a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'can','for', 'from', 'have', 'if', 'in', 'is', 'it', 'may','not', 'of', 'on', 'or', 'tbd', 'that', 'the', 'this','to', 'us', 'we', 'when', 'will', 'with', 'yet','you', 'your', '的', '了', '和','or', 'tbd', 'that', 'the', 'this','to', 'us', 'we', 'when', 'will','when']

Counter(text).most_common(10)#[('when', 3), ('to', 2), ('we', 2), ('that', 2), ('tbd', 2), ('this', 2), ('us',2), ('will', 2), ('the', 2), ('or', 2)]

Counter类是dict的子类,接受参数可以是iterable或者mapping.Counter是一个无序的集合。

c = Counter() #一个新的空的Counter

c = Counter('kwejrkhdskf') #以可迭代对象'kwejrkhdskf'为基础创建Counter

c = Counter({'red': 4, 'blue': 2}) #以mapping{'red': 4, 'blue': 2}为基础创建Counter

c = Counter(cats=4, dogs=8) #以keywords args为基础创建Counter

如果索引的key不存在,Counter类不会报一个KeyError,相应地,它扩展了dict类,如果索引的key不存在,则返回0,如果key存在,则返回对应的值。

>>> c = Counter(['eggs', 'ham','eggs'])>>> c['bacon']

0#在c.keys中不存在'bacon',故返回0

>>> c['eggs']2 #在c.keys中存在'bacon'&

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值