集合模块简明介绍

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

collections 模块提供了许多用于数据处理的实用对象。本部分简要介绍其中一些功能。

示例:统计数量

假设你想要将每只股票的总股数制成表格。

portfolio = [
    ('GOOG', 100, 490.1),
    ('IBM', 50, 91.1),
    ('CAT', 150, 83.44),
    ('IBM', 100, 45.23),
    ('GOOG', 75, 572.45),
    ('AA', 50, 23.15)
]

此列表中有两条 IBM 记录和两条 GOOG 记录。需要以某种方式将股数合并在一起。

计数器

解决方案:使用 Counter

from collections import Counter
total_shares = Counter()
for name, shares, price in portfolio:
    total_shares[name] += shares

total_shares['IBM']     ## 150

示例:一对多映射

问题:你想要将一个键映射到多个值。

portfolio = [
    ('GOOG', 100, 490.1),
    ('IBM', 50, 91.1),
    ('CAT', 150, 83.44),
    ('IBM', 100, 45.23),
    ('GOOG', 75, 572.45),
    ('AA', 50, 23.15)
]

与上一个示例类似,键 IBM 应该有两个不同的元组。

解决方案:使用 defaultdict

from collections import defaultdict
holdings = defaultdict(list)
for name, shares, price in portfolio:
    holdings[name].append((shares, price))
holdings['IBM'] ## [ (50, 91.1), (100, 45.23) ]

defaultdict 确保每次你访问一个键时都会得到一个默认值。

示例:记录历史

问题:我们想要记录最近 N 件事情的历史。解决方案:使用 deque

from collections import deque

history = deque(maxlen=N)
with open(filename) as f:
    for line in f:
        history.append(line)
     ...

collections 模块可能是处理诸如制表和索引等特殊用途数据处理问题最有用的库模块之一。

在本练习中,我们将看几个简单的示例。首先运行你的 report.py 程序,以便在交互模式下加载股票投资组合。

$ python3 -i report.py

练习 2.18:使用计数器制表

假设你想要统计每只股票的总股数。使用 Counter 对象很容易做到这一点。试试看:

>>> portfolio = read_portfolio('portfolio.csv')
>>> from collections import Counter
>>> holdings = Counter()
>>> for s in portfolio:
        holdings[s['name']] += s['shares']

>>> holdings
Counter({'MSFT': 250, 'IBM': 150, 'CAT': 150, 'AA': 100, 'GE': 95})
>>>

仔细观察 portfolioMSFTIBM 的多个条目在这里是如何合并为一个条目的。

你可以像使用字典一样使用计数器来获取单个值:

>>> holdings['IBM']
150
>>> holdings['MSFT']
250
>>>

如果你想对这些值进行排序,可以这样做:

>>> ## 获取持有量最多的三只股票
>>> holdings.most_common(3)
[('MSFT', 250), ('IBM', 150), ('CAT', 150)]
>>>

让我们获取另一个股票投资组合并创建一个新的计数器:

>>> portfolio2 = read_portfolio('portfolio2.csv')
>>> holdings2 = Counter()
>>> for s in portfolio2:
          holdings2[s['name']] += s['shares']

>>> holdings2
Counter({'HPQ': 250, 'GE': 125, 'AA': 50, 'MSFT': 25})
>>>

最后,让我们通过一个简单的操作将所有持有量合并起来:

>>> holdings
Counter({'MSFT': 250, 'IBM': 150, 'CAT': 150, 'AA': 100, 'GE': 95})
>>> holdings2
Counter({'HPQ': 250, 'GE': 125, 'AA': 50, 'MSFT': 25})
>>> combined = holdings + holdings2
>>> combined
Counter({'MSFT': 275, 'HPQ': 250, 'GE': 220, 'AA': 150, 'IBM': 150, 'CAT': 150})
>>>

这只是计数器功能的一小部分。然而,如果你发现自己需要对值进行制表,你应该考虑使用它。

评论:collections 模块

collections 模块是 Python 中最有用的库模块之一。实际上,我们可以专门针对它做一个扩展教程。然而,现在这样做也会分散注意力。目前,把 collections 列入你之后的睡前读物清单吧。

总结

恭喜你!你已经完成了“集合模块”实验。你可以在 LabEx 中练习更多实验来提升你的技能。