Python Collections Module


Python语言在设计之初,使用了一个非常有用的特性叫做——modular programming(模块化编程)。基于这种语言特性,写程序就会像搭积木一样简单。而Python中实现模块化编程的工具有functions,modules,package。而今天要学习的collections就是一个非常重要的module

介绍

在开始学习collections之前,先来了解一下modulepackage的概念(这是小杨一直想要了解的东西,这次一定要学会/(ㄒoㄒ)/~~)

Module

简单理解就是一个module_name.py文件,可以被其他文件通过import进行使用。

# import the library
import math#Using it for taking the log
math.log(10)
2.302585092994046

Python语言本身就自带了成千上万个module了,可以通过这里查看。其中,每个module都有两个built-in函数——dir()help()

  • dir()的作用是返回这个module里面包含的所有方法的方法名。

    print(dir(math))

  • help()用于显示某个function的含义

    help(math.factorial)

Package

package就是一堆“打包起来”的相关的module。例如Numpy和Scipy就是非常常见的机器学习package,它们里面有成千上万个modules。下图是Scipy中包含的sub-packages:

Collections Module

Collections是一个built-in Python module,用于对Python built-in containers(比如dict,list,set,tuple)进行扩展。

一些有用的data structures如下:

1. namedtuple

人如其名,命名tuple。给tuple的每个index指定一个名字,联想一下数据库中的tuple~

from collections import namedtuple
fruit = namedtuple('fruit','number variety color')
guava = fruit(number=2,variety='HoneyCrisp',color='green')
apple = fruit(number=5,variety='Granny Smith',color='red')

2. Counter

用到再说

3. defaultdict

The point of difference is that defaultdict takes the first argument (default_factory) as a default data type for the dictionary.

在传统dict下执行下面的代码:

d = {}
print(d['A'])

使用defaultdict:

from collections import defaultdict
d = defaultdict(object)
print(d['A'])<object object at 0x7fc9bed4cb00>

发现了吗?当访问不存在的key时,dict会报错,但是defaultdict会自动创建一个默认类型的空对象。

4. OrderedDict

相比较传统的dict,OrderedDict的特点体现在一个Ordered上,这里的Ordered是指:它能够记得key插入的顺序,当你访问它的key时,它不会乱序返回,而是按照插入时的次序返回。

  • regular dictionary
d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
  • dictionary sorted by key
OrderedDict(sorted(d.items(), key=lambda t: t[0]))OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
  • dictionary sorted by value
OrderedDict(sorted(d.items(), key=lambda t: t[1]))OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
  • dictionary sorted by the length of the key string
OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))OrderedDict([('pear', 1), ('apple', 4), ('banana', 3), ('orange', 2)])

A point to note here is that in Python 3.6, the regular dictionaries are insertion ordered i.e dictionaries remember the order of items inserted. Read the discussion here.

总结

加油(ง •_•)ง

学到一个新的词组——general purpose,通用的。

参考资料

  1. Python’s Collections Module — High-performance container data types.

文章作者: CarlYoung
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 CarlYoung !
 上一篇
Shallow vs Deep Copying of Python Objects Shallow vs Deep Copying of Python Objects
在做NLP实验,进行数据预处理的时候,用到了字典对象之间的assignment,调试的时候发现数据不太对,通过查阅资料发现,原来Python中的assignment也是另有玄机,除此之外,还有shallow copy和deep copy两种
2021-04-02
下一篇 
深度学习中的logits是什么? 深度学习中的logits是什么?
在深度学习编码的过程中,常常会遇见一些变量名叫做logits,这个logits到底指代了一个什么东西呢?查阅资料之后,我在Google的machine learning文档中找到了定义: LogitsThe vector of raw (
2021-04-02
  目录