上一篇文章: Python实用技法第10篇:对切片命名
下一篇文章: Python实用技法第12篇:经过公共键对字典列表排序:itemgetter
咱们有一个元素序列,想知道在序列中出现次数最多的元素是什么?
collections模块中国的Counter类正是为此类问题而设计的。它甚至有一个很是方便的most_common()方法能够告诉咱们答案。能够给Counter对象提供任何可哈希的对象序列做为输入。segmentfault
from collections import Counter words=[ 'a','b','c','d','e','f', 'a','b','c','d','e','f', 'a','b','c', 'a','b', 'a' ] #利用Counter统计每一个元素出现的个数 words_counts=Counter(words) #出现次数最多的3个元素 top_three=words_counts.most_common(3) #返回元素和出现次数 print(top_three) #Counter底层是一个字典,能够在元素和他们出现的次数之间作映射,例如: #输出元素【f】出现的次数 print(words_counts['f']) #若是想手动增长计数个数,只须要简单的自增 words_counts['f']+=1 print(words_counts['f']) #若是想手动增长计数个数,还能够使用update()方法: #只针对元素【f】增长一次计数 words_counts.update('f') print(words_counts['f']) #为全部计数增长一次 morewords=[ 'a','b','c','d','e','f' ] words_counts.update(morewords) print(words_counts['f'])
运行结果:设计
[('a', 5), ('b', 4), ('c', 3)] 2 3 4 5
from collections import Counter words1=[ 'a','b','c','d','e','f', 'a','b','c','d','e','f', 'a','b','c', 'a','b', 'a' ] words2=[ 'a','b','c','d','e','f', 'a','b','c', 'a','b', 'a' ] one=Counter(words1) two=Counter(words2) print(one) print(two) three=one+two print(three) four=one-two print(four)
运行结果:code
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 2, 'f': 2}) Counter({'a': 4, 'b': 3, 'c': 2, 'd': 1, 'e': 1, 'f': 1}) Counter({'a': 9, 'b': 7, 'c': 5, 'd': 3, 'e': 3, 'f': 3}) Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1})
上一篇文章: Python实用技法第10篇:对切片命名
下一篇文章: Python实用技法第12篇:经过公共键对字典列表排序:itemgetter