如何使用python3 的 collections 模块/库,Container datatypes

0. 简介

  1. 核心原理与基础信息
  2. 常用功能/函数
    2.1. namedtuple: 命名一个不变列表,简洁的class用法
    2.2 deque 高效增删改双向列表
    2.3 defaultdict key不存在时,返回默认值
    2.4 OrderedDict 有序词典,就是加了个顺序而已
    2.5 Counter 计数

1. 核心原理与基础信息

  1. 核心:有点像个罐子(叫container),里面可以装dict, list, set, and tuple.然后做一些操作。

  2. 注意有点像 以上四类的一个子集,例如 namedtuple() ∈ tuple() ; 如果 g ∈ namedtuple(), 那么g ∈ namedtuple() ∈ tuple() 。其他类似。

subset.png
  1. collections中包含什么函数/功能?
# input
import collections
print(dir(collections))

#output 
['AsyncGenerator', 'AsyncIterable', 'AsyncIterator', 'Awaitable', 'ByteString', 'Callable', 'ChainMap', 'Collection', 'Container', 'Coroutine', 'Counter', 'Generator', 'Hashable', 'ItemsView', 'Iterable', 'Iterator', 'KeysView', 'Mapping', 'MappingView', 'MutableMapping', 'MutableSequence', 'MutableSet', 'OrderedDict', 'Reversible', 'Sequence', 'Set', 'Sized', 'UserDict', 'UserList', 'UserString', 'ValuesView', '_Link', '_OrderedDictItemsView', '_OrderedDictKeysView', '_OrderedDictValuesView', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_chain', '_class_template', '_collections_abc', '_count_elements', '_eq', '_field_template', '_heapq', '_iskeyword', '_itemgetter', '_proxy', '_recursive_repr', '_repeat', '_repr_template', '_starmap', '_sys', 'abc', 'defaultdict', 'deque', 'namedtuple']

2. 常用功能

2.1. namedtuple: 命名一个不变列表,简洁的class用法

  1. 例如我想定义一个三维坐标(x,y,z),可以给他起个名字P3。
  2. 调用tuple元素方式不一样,例如调用三维点a中x轴的值,用a.x, 不能用a[0]。
  3. 这样定义的元素,既属于tuple,又属于P3.

代码1-namedtuple

# input code 
#namedtuple in collections 

from collections import namedtuple

three_diamention_Point = namedtuple('three_diamention_Point',['x','y','z'])

a = three_diamention_Point(1,2,3)
print('point a is : \n',a)
print('the valus on the x axis is : \n', a.x)
#output
point a is : 
 three_diamention_Point(x=1, y=2, z=3)
the valus on the x axis is : 
 1
#check the type
print(isinstance(a,three_diamention_Point))
print(isinstance(a,tuple))

#output 
True
True

代码2-make赋值

>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)

代码3-更改值

>>> p = Point(x=11, y=22)
>>> p._replace(x=33)
Point(x=33, y=22)

代码4-tuple回顾

# input code 
b = (1,2,3)
print(type(b))
print(b[0])
#output 
<class 'tuple'>
1

2.2 deque 高效增删改双向列表

  1. 类似list,就是在list外面加个deque()定义。好处就是增删改比list快很多。用法差不多。
  2. 适用于队列和栈,例如poppopleft
# input 
from collections import deque
q = deque(['a', 'b', 'c'])
print(dir(deque))

#output
['append', 'appendleft', 'clear', 'copy', 'count', 'extend', 'extendleft', 
'index', 'insert', 'maxlen', 'pop', 'popleft', 'remove', 'reverse', 'rotate']
  1. 反向打印出元素 reversed(),不对原表做操作。跟list类似

3.1 deque

# IN python3.6 
from collections import deque

d =  deque(['a', 'b', 'c'])
c = list(reversed(d))
print(c)
print(d)

# OUT 
['c', 'b', 'a']
deque(['a', 'b', 'c'])

3.2 list

# IN
a = ('a','b','c')
b = list(reversed(a))
print(a)
print(b)

# OUT 
('a', 'b', 'c')
['c', 'b', 'a']
  1. 其他判断存在与否,一次性插入大量元素等等
>>> 'h' in d                         # search the deque
True
>>> d.extend('jkl')                  # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1)                      # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1)                     # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

>>> deque(reversed(d))               # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear()                        # empty the deque
>>> d.pop()                          # cannot pop from an empty deque
Traceback (most recent call last):
    File "<pyshell#6>", line 1, in -toplevel-
        d.pop()
IndexError: pop from an empty deque

>>> d.extendleft('abc')              # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])

2.3 defaultdict key不存在时,返回默认值

>>> from collections import defaultdict
>>> dd = defaultdict(lambda: 'N/A')
>>> dd['key1'] = 'abc'
>>> dd['key1'] # key1存在
'abc'
>>> dd['key2'] # key2不存在,返回默认值
'N/A'

2.4 OrderedDict 有序词典,就是加了个顺序而已

不过Python3.6 开始dict也是有序的,我就说我写了N个例子都是有序...

可以用来写 先进先出 的FIFO

2.5 Counter 计数

好方便,一定要记住。用来计数,可以算字符串,数组list,词典dict,等等。想到就能用的功能。最好用的有most_common([n])

  1. 字符串
# Uses python 3.6 for strings, test 1 
from collections import Counter

c = Counter()

for ch in 'shlasdlan':
    c[ch] +=  1

print(isinstance(c,Counter))
print(isinstance(c,dict))
print(c)
# test 1 output 
True
True
Counter({'s': 2, 'l': 2, 'a': 2, 'h': 1, 'd': 1, 'n': 1})
  1. list 类似
#In 
from collections import Counter

cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    cnt[word] += 1

print(cnt)

#Out 
Counter({'blue': 3, 'red': 2, 'green': 1})
  1. 引用正则,一行就能对整个文件计数
# IN Uses python 3.6
from collections import Counter
import re
words = re.findall(r'\w+',open('mbox-short.txt').read().lower())
print(Counter(words).most_common(3))

# Out 
[('edu', 461), ('2008', 380), ('jan', 352)]
  1. 可以随便写的函数
>>> from collections import Counter
>>> c = Counter('gallahad')
>>> c
Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
>>> c = Counter({'red': 4, 'blue': 2})
>>> c
Counter({'red': 4, 'blue': 2})
>>> c = Counter(cats=4, dogs=8)
>>> c
Counter({'dogs': 8, 'cats': 4})
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> c
Counter({'a': 4, 'b': 2, 'c': 0, 'd': -2})
  1. elements() 小于零时不显示
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
  1. Counter()还能加减乘除和逻辑运算
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                       # add two counters together:  c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d                       # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d                       # intersection:  min(c[x], d[x]) 
Counter({'a': 1, 'b': 1})
>>> c | d                       # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})

[2018.5.10]
参考资料:

  1. python官方文档 https://docs.python.org/3/library/collections.html

  2. 廖雪峰-python3-collections

  3. In Python 3.6 regular dicts are ordered and more compact

  4. What’s New In Python 3.6

遗留问题:
chainmap暂时不会用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • The Python Data Model If you learned another object-orien...
    plutoese阅读 1,684评论 0 51
  • 在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据...
    不_一阅读 468评论 0 0
  • 本系列主要学习Python的基本使用和语法知识,后续可能会围绕着AI学习展开。Python3 (1) Python...
    猿来如痴阅读 1,262评论 0 1
  • 记得刚来厦时22岁:正青春时,想法出奇的简单,就想来看看,后来进了ZY,大家都在讲一个大学生怎么下车间呢?我呵呵一...
    米挺阅读 126评论 0 2
  • 结婚一个月有什么感觉,感觉就是棒极了。老公有很多生活习惯让我看不惯,臭脚、乱扔袜子。。有时候自己在想,在这么多候...
    提笔忘字2016阅读 173评论 0 0