Python—>(10)学习笔记

Collection模块

collections 是 Python 内建的一个集合模块,提供了许多有用的集合类。

>>> import collections

Counter类

Counter 是一个有助于 hashable 对象计数的 dict 子类。它是一个无序的集合,其中 hashable 对象的元素存储为字典的键,它们的计数存储为字典的值,计数可以为任意整数,包括零和负数。
Counter帮助信息
Counter 示例:查看 Python 的 LICENSE 文件中某些单词出现的次数。

>>> from collections import Counter
>>> import re
>>> path = '/usr/lib/python3.5/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())
['b','b','a', 'a', 'a', 'a']

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

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

defaultdict类

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

>>> 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 对象不存在某个键,它会自动创建一个空列表。

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

来源:实验楼

发布了33 篇原创文章 · 获赞 1 · 访问量 1241

猜你喜欢

转载自blog.csdn.net/weixin_44783002/article/details/104638770