前期回顧
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]
之後的訪問就很簡單了 :)