python(3)-计数器,有序字典
计数器:Counter
在使用计数器之前需要先 import collections
>>> import collections >>> obj = collections.Counter("abcde") >>> print(obj) Counter({'b': 1, 'a': 1, 'c': 1, 'e': 1, 'd': 1}) #分别统计每个字符出现的次数 >>> type(obj) <class 'collections.Counter'> #是计数器类型
遍历计数器
>>> for k in obj.elements(): ... print(k) ... b a c e d
有序字典
定义
>>> dic = collections.OrderedDict() >>> type(dic) <class 'collections.OrderedDict'>
添加元素
>>> dic["k1"] = "v1" >>> dic["k2"] = "v2" >>> dic["k3"] = "v3" >>> print(dic) OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
move_to_end() 将元素移到 最后
>>> dic.move_to_end("k1") >>> print(dic) OrderedDict([('k2', 'v2'), ('k3', 'v3'), ('k1', 'v1')])
删除元素
>>> dic.popitem() #按顺序删除元素,从最后一个开始 ('k1', 'v1') >>> dic.popitem() ('k3', 'v3')
删除特定元素 pop()
>>> print(dic) OrderedDict([('k2', 'v2'), ('k1', 'v1'), ('k3', 'v3')]) >>> dic.pop('k1') 'v1' >>> print(dic) OrderedDict([('k2', 'v2'), ('k3', 'v3')])
更新字典 update()
>>> dic.update({"k4":"v4"}) >>> print(dic) OrderedDict([('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')])
遍历字典
>>> for i in dic.keys(): #遍历所有的key ... print(i) ... k2 k3 k4 >>> for i in dic.values(): #遍历所有的值 ... print(i) ... v2 v3 v4 >>> for k,v in dic.items(): #遍历所有的键值 ... print(k,v) ... k2 v2 k3 v3 k4 v4