day3 collections(counter(对字典的加工) 有序字典(orderedDict)默认字典(defaultdict))可命名元组(namedtuple)

import  collections

 

counter 对字典的加工处理  计算序列内元素出现的次数

>>> import collections
>>> obj = collections.Counter('abcdegdangrareg')
>>> print obj
Counter({'a': 3, 'g': 3, 'e': 2, 'd': 2, 'r': 2, 'c': 1, 'b': 1, 'n': 1})

 

most_common

>>> print obj
Counter({'a': 3, 'g': 3, 'e': 2, 'd': 2, 'r': 2, 'c': 1, 'b': 1, 'n': 1})
>>> ret = obj.most_common(4)
>>> print ret
[('a', 3), ('g', 3), ('e', 2), ('d', 2)]
>>>
View Code

elements   循环conter内的内容的(原生的值为进行过加工处理)  obj(已经处理完的)

>>> for item in obj.elements():
... print item
...
a
a
a
c

....

>>> for k,v in obj.items():
... print k,v
...
a 3
c 1
b 1
e 2

 

update         更新计数器,增加,如果原来没有,则新建。有则加

>>> obj = collections.Counter(['11','22','22','33'])
>>> obj
Counter({'22': 2, '11': 1, '33': 1})
>>> obj.update(['eric','11','11'])
>>> obj
Counter({'11': 3, '22': 2, '33': 1, 'eric': 1})

 

subtract()      删除

>>> obj
Counter({'11': 3, '22': 2, '33': 1, 'eric': 1})
>>> obj.subtract(['eric','11','11'])
>>> obj
Counter({'22': 2, '11': 1, '33': 1, 'eric': 0})
>>> obj.subtract(['eric','11','11'])
>>> obj
Counter({'22': 2, '33': 1, '11': -1, 'eric': -1})
>>>

 

有序字典(orderedDict)

>>> dic = collections.OrderedDict()

>>> dic['k1'] = 'v1'
>>> dic['k2'] = 'v2'
>>> dic['k3'] = 'v3'
>>> dic
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])

 

move_to_end     把谁拿到最后,python3中实现

pop (self, k ,d=None)          删除,自己在拿走一个,挑着拿,还有一个返回值

>>> dic.pop('k1')
'v1'
>>> dic
OrderedDict([('k2', 'v2')])

 

popitem        按照顺序拿(后进先出)

>>> dic
OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
>>> dic.popitem()
('k3', 'v3')

 

setdefault      设置默认值

>>> dic.setdefault('k4')
>>> dic
OrderedDict([('k2', 'v2'), ('k4', None)])
>>> dic.setdefault('k4','v4')
>>> dic
OrderedDict([('k2', 'v2'), ('k4', None)])
>>> dic.setdefault('k5','v5')
'v5'
>>> dic
OrderedDict([('k2', 'v2'), ('k4', None), ('k5', 'v5')])

 

update

>>> dic.update({'k1':'k111','k10':'v10'})
>>> dic
OrderedDict([('k2', 'v2'), ('k4', None), ('k5', 'v5'), ('k1', 'k111'), ('k10', '
v10')])

 

values

 

默认字典(defaultdic)

创建了字典默认值是list列表,(append是列表的方法)

>>> dic = collections.defaultdict(list)
>>> dic['k1'].append('alex')
>>> dic
defaultdict(<type 'list'>, {'k1': ['alex']})

 

可命名元组 (namedtuple) 对元组的加工

元组通过索引访问

可命名元组可以通过名字访问

#自己创建一个MytupleClass类,创建obj对象

>>> MytupleClass = collections.namedtuple('MytupleClass',['x','y','z'])

>>> obj = MytupleClass(11,22,33)
>>> print obj.x
11
>>> print obj.y
22
>>> print obj.z
33

 

你可能感兴趣的:(day3 collections(counter(对字典的加工) 有序字典(orderedDict)默认字典(defaultdict))可命名元组(namedtuple))