Python Collections模块

网友投稿 440 2022-05-30

在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。

1.namedtuple: 生成可以使用名字来访问元素内容的tuple

2.deque: 双端队列,可以快速的从另外一侧追加和推出对象

3.Counter: 计数器,主要用来计数

4.OrderedDict: 有序字典

5.defaultdict: 带有默认值的字典

1、namedtuple

我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成:

>>> p=(2,6)

但是,看到(1, 2),很难看出这个tuple是用来表示一个坐标的。

这时,namedtuple就派上了用场:

from collections import namedtuple point = namedtuple("point", ['x', 'y']) print(point) p_obj = point(6, 8) print(p_obj.x) print(p_obj.y)

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo005.py 6 8 Process finished with exit code 0

类似的,如果要用坐标和半径表示一个圆,也可以用namedtuple定义:

# namedtuple('名称', [属性list]): Circle = namedtuple("Circle", ['x', 'y', 'r']) cir = Circle(8, 6, 10) print(cir.x) print(cir.y) print(cir.r)

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo005.py 8 6 10 Process finished with exit code 0

2、deque

使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。

deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:

from collections import deque q = deque(['a', 'b', 'c']) q.append('d') print(q) q.appendleft('e') print(q) q.pop() print(q) q.popleft() print(q)

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo005.py deque(['a', 'b', 'c', 'd']) deque(['e', 'a', 'b', 'c', 'd']) deque(['e', 'a', 'b', 'c']) deque(['a', 'b', 'c']) Process finished with exit code 0

deque除了实现list的append()和pop()外,还支持appendleft()和popleft(),这样就可以非常高效地往头部添加或删除元素。

3、OrderedDict

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

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

from collections import OrderedDict lis = [('a', 21), ('b', 55), ('c', 86)] dic = dict(lis)  # dict的Key是无序的 print(dic) ord_dic = OrderedDict(lis)  # OrderedDict的Key是有序的 print(ord_dic)

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo005.py {'a': 21, 'b': 55, 'c': 86} OrderedDict([('a', 21), ('b', 55), ('c', 86)]) Process finished with exit code 0

注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:

ord_dic = OrderedDict() ord_dic['z'] = 99 ord_dic['y'] = 110 ord_dic['z'] = 666 print(ord_dic.keys())  # 按照插入的Key的顺序返回

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo005.py odict_keys(['z', 'y']) Process finished with exit code 0

4、defaultdict

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。

即: {'k1': 大于66 , 'k2': 小于66}

lis = [11, 22, 33, 55, 77, 66, 88, 99] dic = {} for value in lis:     if value > 66:         if dic.has_key('k1'):             dic['k1'].append(value)         else:             dic['k1'] = [value]     else:         if dic.has_key('k2'):             dic['k2'].append(value)         else:             dic['k2'] = [value]

from collections import defaultdict lis = [11, 22, 33, 55, 77, 66, 88, 99] my_dic = defaultdict(lis) for value in lis:     if value > 66:         my_dic['k1'].append(value)     else:         my_dic['k2'].append(value) print(my_dic)

使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict:

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

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo005.py abc N/A N/A Process finished with exit code 0

5、Counter

Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。计数值可以是任意的Interger(包括0和负数)。Counter类和其他语言的bags或multisets很相似。

from collections import Counter coun = Counter("absdsdsdadsdsa") print(coun)

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo005.py Counter({'s': 5, 'd': 5, 'a': 3, 'b': 1}) Process finished with exit code 0

Python Collections模块

创建

下面的代码说明了Counter类创建的四种方法:

from collections import Counter c = Counter()  # 创建一个空的Counter类 print(c) c = Counter('g***d')  # 从一个可iterable对象(list、tuple、dict、字符串等)创建 print(c) c = Counter({'a': 4, 'b': 2})  # 从一个字典对象创建 print(c) c = Counter(a=4, b=2)  # 从一组键值对创建 print(c)

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo006.py Counter() Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1}) Counter({'a': 4, 'b': 2}) Counter({'a': 4, 'b': 2}) Process finished with exit code 0

计数值的访问与缺失的键

当所访问的键不存在时,返回0,而不是KeyError;否则返回它的计数。

计数值的访问

from collections import Counter cou = Counter("hello world") print(cou["l"]) print(cou["o"]) print(cou["a"])

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo006.py 3 2 0 Process finished with exit code 0

计数器的更新(update和subtract)

可以使用一个iterable对象或者另一个Counter对象来更新键值。

计数器的更新包括增加和减少两种。其中,增加使用update()方法:

计数器的更新(update)

from collections import Counter cou = Counter("hello world") cou.update("which")  # 使用另一个iterable对象更新 print(cou["h"]) c = Counter("watch") cou.update(c)  # 使用另一个Counter对象更新 print(cou["h"])

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo006.py 3 4 Process finished with exit code 0

减少则使用subtract()方法:

计数器的更新(subtract)

from collections import Counter c = Counter('which') print(c["h"]) c.subtract('witch')  # 使用另一个iterable对象更新 print(c['h']) d = Counter('watch') c.subtract(d)  # 使用另一个Counter对象更新 print(c['a'])

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo006.py 2 1 -1 Process finished with exit code 0

键的修改和删除

当计数值为0时,并不意味着元素被删除,删除元素应当使用del。

键的删除

from collections import Counter c = Counter("abcdcba") print(c) c["b"] = 0 print(c) del c["a"] print(c)

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo006.py Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1}) Counter({'a': 2, 'c': 2, 'd': 1, 'b': 0}) Counter({'c': 2, 'd': 1, 'b': 0}) Process finished with exit code 0

elements()

返回一个迭代器。元素被重复了多少次,在该迭代器中就包含多少个该元素。元素排列无确定顺序,个数小于1的元素不被包含。

elements()方法

from collections import Counter c = Counter(a=4, b=2, c=0, d=-2) print(list(c.elements()))

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo006.py ['a', 'a', 'a', 'a', 'b', 'b'] Process finished with exit code 0

most_common([n])

返回一个TopN列表。如果n没有被指定,则返回所有元素。当多个元素计数值相同时,排列是无确定顺序的。

most_common()方法

from collections import Counter c = Counter('abracadabra') print(c) print(c.most_common()) print(c.most_common(3))

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo006.py Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}) [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)] [('a', 5), ('b', 2), ('r', 2)] Process finished with exit code 0

浅拷贝copy

浅拷贝copy

from collections import Counter c = Counter("abcdcba") print(c) d = c.copy() print(d)

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo006.py Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1}) Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1}) Process finished with exit code 0

算术和集合操作

+、-、&、|操作也可以用于Counter。其中&和|操作分别返回两个Counter对象各元素的最小值和最大值。需要注意的是,得到的Counter对象将删除小于1的元素。

Counter对象的算术和集合操作

from collections import Counter c = Counter(a=3, b=1) d = Counter(a=1, b=2) print(c + d)  # c[x] + d[x] print(c - d)  # subtract(只保留正数计数的元素) print(c & d)  # 交集:  min(c[x], d[x]) print(c | d)  # 并集:  max(c[x], d[x])

结果:

D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo006.py Counter({'a': 4, 'b': 3}) Counter({'a': 2}) Counter({'a': 1, 'b': 1}) Counter({'a': 3, 'b': 2}) Process finished with exit code 0

其他常用操作

下面是一些Counter类的常用操作,来源于Python官方文档

Counter类常用操作

sum(c.values())  # 所有计数的总数 c.clear()  # 重置Counter对象,注意不是删除 list(c)  # 将c中的键转为列表 set(c)  # 将c中的键转为 setdict(c)  # 将c中的键值对转为字典 c.items()  # 转为(elem, cnt)格式的列表 Counter(dict(list_of_pairs))  # 从(elem, cnt)格式的列表转换为Counter类对象 c.most_common()[:-n:-1]  # 取出计数最少的n个元素 c += Counter()  # 移除0和负值

软件开发 人工智能 机器学习 AI

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Excel表格中使用公式怎么提取省份及市
下一篇:HCIE-CLOUD复习第一天
相关文章