Collections 模块

知识点

  • Counter 类
  • defaultdict 类
  • namedtuple 类

在这个实验我们会学习 Collections 模块。这个模块实现了一些很好的数据结构,它们能帮助你解决各种实际问题。

>>> import collections

这是如何导入这个模块,现在我们来看看其中的一些类。

1. Counter

Counter 是一个有助于 hashable 对象计数的 dict 子类。它是一个无序的集合,其中 hashable 对象的元素存储为字典的键,它们的计数存储为字典的值,计数可以为任意整数,包括零和负数。

我们可以这样查看 Counter 的帮助信息,事实上这些信息来源于 Counter 的文档字符串(collections.Counter.__doc__)。

下面我们来看一个例子,例子中我们查看 Python 的 LICENSE 文件中某些单词出现的次数。

1.1. Counter 示例

>>> from collections import Counter
>>> import re
>>> path = '/usr/lib/python3.4/LICENSE.txt'
>>> words = re.findall('\w+', open(path).read().lower())
>>> Counter(words).most_common(10)
[('the', 80), ('or', 78), ('1', 66), ('of', 61), ('to', 50), ('and', 48), ('python', 46), ('in', 38), ('license', 37), ('any', 37)]

Counter 对象有一个叫做 elements() 的方法,其返回的序列中,依照计数重复元素相同次数,元素顺序是无序的。

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

most_common() 方法返回最常见的元素及其计数,顺序为最常见到最少。

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

2. defaultdict

defaultdict 是内建 dict 类的子类,它覆写了一个方法并添加了一个可写的实例变量。其余功能与字典相同。

defaultdict() 第一个参数提供了 default_factory 属性的初始值,默认值为 Nonedefault_factory 属性值将作为字典的默认数据类型。所有剩余的参数与字典的构造方法相同,包括关键字参数。

同样的功能使用 defaultdict 比使用 dict.setdefault 方法快。

defaultdict 用例

>>> from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
dict_items([('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])])

在例子中你可以看到,即使 defaultdict 对象不存在某个,它会自动创建一个空列表。

3. namedtuple

命名元组有助于对元组每个位置赋予意义,并且让我们的代码有更好的可读性和自文档性。你可以在任何使用元组地方使用命名元组。在例子中我们会创建一个命名元组以展示为元组每个位置保存信息。

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y']) # 定义命名元组
>>> p = Point(10, y=20) # 创建一个对象
>>> p
Point(x=10, y=20)
>>> p.x + p.y
30
>>> p[0] + p[1] # 像普通元组那样访问元素
30
>>> x, y = p # 元组拆封
>>> x
10
>>> y
20

总结

这个实验我们使用了 Collections 中的一些数据结构,可能你目前并用不上他,但希望你以后需要的时候会想起它们 : -)

知识点

  • Counter 类
  • defaultdict 类
  • namedtuple 类

在这个实验我们会学习 Collections 模块。这个模块实现了一些很好的数据结构,它们能帮助你解决各种实际问题。

>>> import collections

这是如何导入这个模块,现在我们来看看其中的一些类。

1. Counter

Counter 是一个有助于 hashable 对象计数的 dict 子类。它是一个无序的集合,其中 hashable 对象的元素存储为字典的键,它们的计数存储为字典的值,计数可以为任意整数,包括零和负数。

我们可以这样查看 Counter 的帮助信息,事实上这些信息来源于 Counter 的文档字符串(collections.Counter.__doc__)。

下面我们来看一个例子,例子中我们查看 Python 的 LICENSE 文件中某些单词出现的次数。

1.1. Counter 示例

>>> from collections import Counter
>>> import re
>>> path = '/usr/lib/python3.4/LICENSE.txt'
>>> words = re.findall('\w+', open(path).read().lower())
>>> Counter(words).most_common(10)
[('the', 80), ('or', 78), ('1', 66), ('of', 61), ('to', 50), ('and', 48), ('python', 46), ('in', 38), ('license', 37), ('any', 37)]

Counter 对象有一个叫做 elements() 的方法,其返回的序列中,依照计数重复元素相同次数,元素顺序是无序的。

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

most_common() 方法返回最常见的元素及其计数,顺序为最常见到最少。

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

2. defaultdict

defaultdict 是内建 dict 类的子类,它覆写了一个方法并添加了一个可写的实例变量。其余功能与字典相同。

defaultdict() 第一个参数提供了 default_factory 属性的初始值,默认值为 Nonedefault_factory 属性值将作为字典的默认数据类型。所有剩余的参数与字典的构造方法相同,包括关键字参数。

同样的功能使用 defaultdict 比使用 dict.setdefault 方法快。

defaultdict 用例

>>> from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
dict_items([('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])])

在例子中你可以看到,即使 defaultdict 对象不存在某个,它会自动创建一个空列表。

3. namedtuple

命名元组有助于对元组每个位置赋予意义,并且让我们的代码有更好的可读性和自文档性。你可以在任何使用元组地方使用命名元组。在例子中我们会创建一个命名元组以展示为元组每个位置保存信息。

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y']) # 定义命名元组
>>> p = Point(10, y=20) # 创建一个对象
>>> p
Point(x=10, y=20)
>>> p.x + p.y
30
>>> p[0] + p[1] # 像普通元组那样访问元素
30
>>> x, y = p # 元组拆封
>>> x
10
>>> y
20

总结

这个实验我们使用了 Collections 中的一些数据结构,可能你目前并用不上他,但希望你以后需要的时候会想起它们 : -)

python的Collections 模块的更多相关文章

  1. Python中collections模块

    目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque ChainMap Python中collections ...

  2. Python的collections模块中namedtuple结构使用示例

      namedtuple顾名思义,就是名字+元组的数据结构,下面就来看一下Python的collections模块中namedtuple结构使用示例 namedtuple 就是命名的 tuple,比较 ...

  3. python:collections模块

    Counter类 介绍:A counter tool is provided to support convenient and rapid tallies 构造:class collections. ...

  4. python之collections模块(OrderDict,defaultdict)

    前言: import collections print([name for name in dir(collections) if not name.startswith("_" ...

  5. 转载:Python中collections模块

    转载自:Python中collections模块 目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque Ch ...

  6. Python中collections模块的使用

    本文将详细讲解collections模块中的所有类,和每个类中的方法,从源码和性能的角度剖析. 一个模块主要用来干嘛,有哪些类可以使用,看__init__.py就知道 '''This module i ...

  7. python 之 Collections模块

    官方文档:https://yiyibooks.cn/xx/python_352/library/collections.html 参考: https://blog.csdn.net/songfreem ...

  8. 【python】collections模块(有序字典,计数器,双向队列)

    collections模块基本介绍 我们都知道,Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上 ...

  9. Python中Collections模块的Counter容器类使用教程

    1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict.set.list.tuple以外的一些特殊的容器类型,分别是: OrderedDict类 ...

随机推荐

  1. 【UVA 11426】gcd之和 (改编)

    题面 \(\sum_{i=1}^{n}\sum_{j=1}^m\gcd(i,j)\mod998244353\) \(n,m<=10^7\) Sol 简单的一道莫比乌斯反演题 \(原式=\sum_ ...

  2. [BZOJ3506] [Cqoi2014] 排序机械臂 (splay)

    Description 同OJ1552 Input Output Sample Input Sample Output HINT Source Solution Q:哎不是同一道题吗为什么分两篇博客来 ...

  3. htop命令使用详解

    一.htop 简介 htop 是Linux系统中的一个互动的进程查看器,一个文本模式的应用程序(在控制台或者X终端中),需要ncurses.与Linux传统的top相比,htop更加人性化.它可让用户 ...

  4. Appserv(Apache) 设置网页不显示目录(索引)

    首先在appserv安装目录下找到httpd.conf文件 ./AppServ/Apache24/conf/httpd.conf 打开文件,找到 Options Indexes FollowSymLi ...

  5. ZOJ3946:Highway Project(最短路变形)

    本文转载自:http://www.javaxxz.com/thread-359442-1-1.html Edward, the emperor of the Marjar Empire, wants ...

  6. python格式化输出基础知识(2)

    ---恢复内容开始--- 一:请输入名片  (姓名,年龄,职业,爱好)设计名片 name=input('你的名字')age=input('你的年龄')job=input('你的工作')hobbie=i ...

  7. 关于better-scroll中的问题点

    最近在学习vue和better-scroll结合开发音乐APP,看着视频介绍中在制作slidet轮播图的时候,视频中讲解要想实现无缝滚动,则加入snapLoot:true,但是不可以单独引入它,必须将 ...

  8. 关于js高度和宽度的获取 ----2017-03-29

    来源:百度  对错有待实践检验 网页可见区域宽: document.body.clientWidth 网页可见区域高: document.body.clientHeight 网页可见区域宽: docu ...

  9. fail2ban防止SSH暴力破解

    [root@kazihuo /srv]# wget https://github.com/fail2ban/fail2ban/archive/0.8.14.tar.gz [root@kazihuo / ...

  10. 常用到的html页面布局和组件: 自己用

    1. 用div当作圆 <div style="border: 1px solid blue;height: 100px; width: 100px; border-radius: 20 ...