当前位置:首页 > Python教程 > python技巧

python学习笔记之collections模块的使用

  • namedtuple
  • deque
  • OrderedDict
  • Counter

 

一、namedtuple

用于创建一个自定义的tuple对象,可以用于给数组重命名,提高数组索引可读性。

示例:

>>> from collections import namedtuple
>>> Point = namedtuple(‘Point‘, [‘x‘, ‘y‘])
>>> p = Point(1, 2)
>>> p.x
1
>>> p.y
2

from collections import namedtuple
students=namedtuple(‘Student‘,[‘name‘,‘age‘,‘sex‘,‘email‘])
s2=students(‘sun‘,‘25‘,‘girl‘,‘mesunyueru@qq.com‘)
print(s2.email)

二、deque

deque是一个双向列表,包含append(),pop(),appendleft(),popleft()方法

>>> from collections import deque
>>> q = deque([‘a‘, ‘b‘, ‘c‘])
>>> q.append(‘x‘)
>>> q.appendleft(‘y‘)
>>> q
deque([‘y‘, ‘a‘, ‘b‘, ‘c‘, ‘x‘])

三、OrderedDict

使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。

如果要保持Key的顺序,可以用OrderedDict

>>> from collections import OrderedDict
>>> d = dict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)])
>>> d # dict的Key是无序的
{‘a‘: 1, ‘c‘: 3, ‘b‘: 2}
>>> od = OrderedDict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)])
>>> od # OrderedDict的Key是有序的
OrderedDict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)])

 注意是按照插入的顺序,不是key本身的顺序

四、Counter

 from collections import Counter
>>> c = Counter()
>>> for ch in ‘programming‘:
...     c[ch] = c[ch] + 1
...
>>> c
Counter({‘g‘: 2, ‘m‘: 2, ‘r‘: 2, ‘a‘: 1, ‘i‘: 1, ‘o‘: 1, ‘n‘: 1, ‘p‘: 1})

原文:https://www.cnblogs.com/mesunyueru/p/9196071.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐