翻译:《实用的 Python 编程》02_05_Collections - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Gude
codists

翻译:《实用的 Python 编程》02_05_Collections

  •  
  •   codists
    codists 2021 年 2 月 24 日 1946 次点击
    这是一个创建于 1884 天前的主题,其中的信息可能已经有所发展或是发生改变。

    2.5 collections 模块

    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 ,以便在交互模式下能够加载股票投资组合。

    bash % python3 -i report.py 

    练习 2.18:使用 Counter 模块表格化

    假设需要将每支股票的份额总数表格化,那么使用 Counter 对象会很容易。试试看:

    >>> portfolio = read_portfolio('Data/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}) >>> 

    仔细观察portfolio 中的 MSFTIBM 的多个条目是如何合并的。

    可以像字典一样使用 Counter 模块检索单个值。

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

    如果想要对值排名,这样做:

    >>> # Get three most held stocks >>> holdings.most_common(3) [('MSFT', 250), ('IBM', 150), ('CAT', 150)] >>> 

    让我们获取另一个股票投资组合并生成一个新的 Counter 对象:

    >>> portfolio2 = read_portfolio('Data/portfolio2.csv') >>> holdings2 = Counter() >>> for s in portfolio2: holdings2[s['name']] += s['shares'] >>> holdings2 Counter({'HPQ': 250, 'GE': 125, 'AA': 50, 'MSFT': 25}) >>> 

    最后,通过一个简单的操作把所有的 holdings 变量合并。

    >>> 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}) >>> 

    这只是对 Counter 功能的一个小尝试,如果发现需要对值进行表格化,那么就应该考虑使用它。

    说明:collections 模块

    collections 模块是 Python 所有库中最有用的库模块之一。实际上,我们可以为此做一个拓展教程,但是,现在这样做会分散注意力。从现在开始,把collections列为你的睡前读物,以备后用。

    注:完整翻译见 https://github.com/codists/practical-python-zh

    2 条回复    2021-02-25 14:28:21 +08:00
    yangfan1999
        1
    yangfan1999  
       2021 年 2 月 25 日
    已 star,学习学习。
    codists
        2
    codists  
    OP
       2021 年 2 月 25 日
    @yangfan1999
    感谢支持,期待有机会与大佬多多交流。
    /div>
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     4711 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 37ms UTC 04:03 PVG 12:03 LAX 21:03 JFK 00:03
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86