namedtuple 能够创建和 tuple 类似的对象,只是 namedtuple 类本身和对应元素都可以具有一个名字,有点类似于没有方法的普通类。
from collections import namedtuple
# 定义一个namedtuple类型User,并包含name,sex和age属性。
User = namedtuple('User', ['name', 'sex', 'age'])
# 创建一个User对象
user = User(name='kongxx', sex='male', age=21)
# 也可以通过一个list来创建一个User对象,这里注意需要使用"_make"方法
user = User._make(['kongxx', 'male', 21])
print user
# User(name='user1', sex='male', age=21)
# 获取用户的属性
print user.name
print user.sex
print user.age
# 修改对象属性,注意要使用"_replace"方法
user = user._replace(age=22)
print user
# User(name='user1', sex='male', age=22)
# 将User对象转换成字典,注意要使用"_asdict"
print user._asdict()
# OrderedDict([('name', 'kongxx'), ('sex', 'male'), ('age', 22)])
内部实现的双向队列,基本操作如下
from collections import deque
d = deque([1,2,3])
d.extendleft(['a','b','c'])
print(d)
deque(['c', 'b', 'a', 1, 2, 3])
hainMap是python3的新特性,它用来将多个map组成一个新的单元(原来的map结构仍然存在,类似于这些map被存在了一个list之中),这比新建一个map再将其他map用update加进来快得多。通过ChainMap可以来模拟嵌套的情景,而且多用于模板之中。
ChainMap支持普通map的所有操作,下面主要展示一下它的特性:
# 新建ChainMap及它的结构
In[2]: from collections import ChainMap
In[3]: m1 = {'color': 'red', 'user': 'guest'}
In[4]: m2 = {'name': 'drfish', 'age': '18'}
In[5]: chainMap = ChainMap(m1, m2)
In[6]: print(chainMap.items())
ItemsView(ChainMap({'user': 'guest', 'color': 'red'}, {'age': '18', 'name': 'drfish'}))
# 获取ChainMap中的元素
In[7]: print(chainMap.get('name'))
drfish
In[8]: print(chainMap.get('not'))
None
# 新增map
In[9]: m3 = {'data': '1-6'}
In[10]: chainMap = chainMap.new_child(m3)
In[11]: print(chainMap.items())
ItemsView(ChainMap({'data': '1-6'}, {'user': 'guest', 'color': 'red'}, {'age': '18', 'name': 'drfish'}))
# parents属性
In[12]: print(chainMap.parents)
ChainMap({'user': 'guest', 'color': 'red'}, {'age': '18', 'name': 'drfish'})
In[13]: print(chainMap.parents.parents)
ChainMap({'age': '18', 'name': 'drfish'})
In[14]: print(chainMap.parents.parents.parents)
ChainMap({})
# maps属性
In[15]: chainMap.maps
Out[15]:
[{'data': '1-6'},
{'color': 'red', 'user': 'guest'},
{'age': '18', 'name': 'drfish'}]
字典的子类,记录可哈希对象出现的次数
首先 Counter 有多种初始化方式
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
主要的操作范例如下
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
>>> c.most_common(3) # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c) # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements())) # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values()) # total of all counts
15
>>> c['a'] # count of letter 'a'
5
>>> for elem in 'shazam': # update counts from an iterable
... c[elem] += 1 # by adding 1 to each element's count
>>> c['a'] # now there are seven 'a'
7
>>> del c['b'] # remove all 'b'
>>> c['b'] # now there are zero 'b'
0
>>> d = Counter('simsalabim') # make another counter
>>> c.update(d) # add in the second counter
>>> c['a'] # now there are nine 'a'
9
>>> c.clear() # empty the counter
>>> c
Counter()
Note: If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:
>>> c = Counter('aaabbc')
>>> c['b'] -= 2 # reduce the count of 'b' by two
>>> c.most_common() # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]
逻辑操作
>>> c = Counter('which')
>>> c.subtract('witch') # subtract elements from another iterable
>>> c.subtract(Counter('watch')) # subtract elements from another counter
>>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
-1
>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})
>>> Counter('abbbc') - Counter('bccd')
Counter({'b': 2, 'a': 1})
>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1})
>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
提供一个有序的字典,从而可以实现遍历操作。内部存储顺序根据传入顺序给定。
import collections
print 'Regular dictionary:'
d1={}
d1['a']='A'
d1['b']='B'
d1['c']='C'
d2={}
d2['c']='C'
d2['a']='A'
d2['b']='B'
print d1==d2
print '\nOrderedDict:'
d1=collections.OrderedDict()
d1['a']='A'
d1['b']='B'
d1['c']='C'
d2=collections.OrderedDict()
d2['c']='C'
d2['a']='A'
d2['b']='B'
print d1==d2
创建一个带默认值的字典,默认值根据传入的工厂函数
from collections import defaultdict
dict1 = defaultdict(int)
dict2 = defaultdict(set)
dict3 = defaultdict(str)
dict4 = defaultdict(list)
dict1[2] ='two'
print(dict1[1])
print(dict2[1])
print(dict3[1])
print(dict4[1])
'''
0
set()
[]
'''