前期回顾
python collections模块中的Counter、OrderedDict、namedtuple、ChainMap、deque
问题引入
在学习完python 中的 collections模块后,我们会遇到如何访问内部某一具体元素的问题,查找网上没有相关博文,故解决此问题。
代码解决
from collections import Counter
s = "aaabcccdeff"
temp = Counter(s)
print(temp) # Counter({'a': 3, 'c': 3, 'f': 2, 'b': 1, 'd': 1, 'e': 1})
print(type(temp)) # <class 'collections.Counter'>
print(temp.items()) # dict_items([('a', 3), ('b', 1), ('c', 3), ('d', 1), ('e', 1), ('f', 2)])
print(temp.keys()) # dict_keys(['a', 'b', 'c', 'd', 'e', 'f'])
print(temp.values()) # dict_values([3, 1, 3, 1, 1, 2])
# dict.keys()转换成list类型
print(list(temp.keys())) # ['a', 'b', 'c', 'd', 'e', 'f']
# dict_values转化为list类型
print(list(temp.values())[:]) # [3, 1, 3, 1, 1, 2]
之后的访问就很简单了 :)
本文深入探讨Python中collections模块的使用,重点介绍了Counter类的特性及其在数据统计中的应用。通过实例演示了如何利用Counter进行字符频率统计,并展示了如何访问Counter对象的元素、键和值。
7147

被折叠的 条评论
为什么被折叠?



