看到collections.namedtuple()函数,顺便学习一下
1.namedtuple
创建一个具名元组子类,可以使用名字(属性)来引用元组中的值
>>> import collections
>>> node = collections.namedtuple('position',['x','y'])
>>> node
<class '__main__.position'>
>>> p = node(1,5)
>>> p
position(x=1, y=5)
>>> p.x
1
>>> p.y
5
2.Counter
创建一个字典子类,用于计数,统计字符(特定对象)出现的次数
>>> url = 'http://write.blog.csdn.net/postedit'
>>> counter = collections.Counter()
>>> for i in url:
counter[i] += 1
>>> counter
Counter({'t': 6, '/': 3, 'e': 3, '.': 3, 'p': 2, 'i': 2, 'o': 2, 's': 2, 'd': 2, 'n': 2, 'h': 1, ':': 1, 'w': 1, 'r': 1, 'b': 1, 'l': 1, 'g': 1, 'c': 1})
3.defaultdict
创建一个带有默认值的字典,如果引用时key不存在,则返回默认值
>>> d_dict = collections.defaultdict(lambda:'no key')
>>> d_dict[1] = 1
>>> d_dict[1]
1
>>> d_dict[2]
'no key'
4.deque
创建一个双向队列(列表),可以从队列的两侧添加或删除元素
>>> d_q = collections.deque([1,2,3])
>>> d_q.append(4)
>>> d_q
deque([1, 2, 3, 4])
>>> d_q.appendleft(4)
>>> d_q
deque([4, 1, 2, 3, 4])
>>> d_q.popleft()
4
>>> d_q
deque([1, 2, 3, 4])
5.OrderedDict
创建一个Key排列有序的字典,顺序为Key加入的顺序
puthon3.6之后常规的 dict( ) 中的键也是有序的了,看起来没什么作用
https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation
这里说:
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon