前期回顾
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]
之后的访问就很简单了 :)