由于最近对机器学习算法感兴趣,一直知道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'&