推荐学习书目
› 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 Guide
Contextualist
V2EX  ›  Python

最近发现 defaultdict 的一个奇技淫巧

  •  
  •   Contextualist ·
    Contextualist · Mar 7, 2021 · 4148 views
    This topic created in 2073 days ago, the information mentioned may be changed or developed.

    配合自身 len 可以做一个去重的自增索引:

    >>> from collections import defaultdict
    >>> ind = defaultdict(lambda: len(ind))
    >>> ind["test_a"]
    0
    >>> ind["test_b"]
    1
    >>> ind["test_a"]
    0
    >>> ind["test_z"]
    2
    
    15 replies  •  2021-03-09 17:19:40 +08:00
    ClericPy
    ClericPy
    Mar 7, 2021
    1
    有意思, 用的跟个 Enum 似的
    aijam
    aijam
    Mar 7, 2021
    2
    点赞
    shutongxinq
    shutongxinq
    Mar 7, 2021
    3
    有意思,赞!
    iConnect
    iConnect
    Mar 7, 2021 via Android
    4
    赶紧想想,有哪些使用场景,性能好不好?
    laoyuan
    laoyuan
    Mar 7, 2021
    5
    性能,性能是关键
    24bit
    24bit
    Mar 7, 2021
    6
    有意思
    Contextualist
    Contextualist
    OP
    Mar 7, 2021
    7
    @iConnect @laoyuan
    就 CPython 来说,defaultdict 和 dict 的实现几乎是一样的,前者只是多了个处理键值缺失的方法(__missing__)。这就意味着:1) 如果查找的键存在,其效率和 dict 一样; 2) 否则调用 len ( O(1),因为这是对象自己维护的一个属性),并插入一对值。
    abersheeran
    abersheeran
    Mar 7, 2021
    8
    很有趣。
    abersheeran
    abersheeran
    Mar 7, 2021
    9
    jokeface
    jokeface
    Mar 7, 2021
    10
    为什么不会报错,感觉 ind 这个变量应该没有哇
    xoyo
    xoyo
    Mar 7, 2021
    11
    @jokeface deferred evaluate
    xiaolinjia
    xiaolinjia
    Mar 8, 2021
    12
    在 py37 的 dict 有序后,这样就能按插入顺序取到索引吧。不过这个得先转 list 性能较差。
    >>> a = {'a': 'aaa', 'b': 'bbb'}
    >>> list(a).index('a')
    0
    no1xsyzy
    no1xsyzy
    Mar 8, 2021
    13
    @iConnect @laoyuan
    性能甚至应当比
    if key not in ind: ind[key] = len(ind)
    好,因为 call __missing__ 的过程不需要走 python 代码。

    倒是线程安全? asyncio 之类的协程非抢占式调度倒是没问题,抢占式的线程恐怕会造成问题。
    Contextualist
    Contextualist
    OP
    Mar 8, 2021
    14
    @no1xsyzy 好观点。查了一下,这样(在 CPython 中)似乎的确不是线程安全的,因为如果工厂函数是 Python 代码,调用它的这个动作就是一个线程切换点。详见 https://stackoverflow.com/a/17682555,按照这个回答的提示,或许下面这个不优雅写法能行?
    ind = defaultdict()
    ind.default_factory = ind.__len__
    vegetableChick
    vegetableChick
    Mar 9, 2021
    15
    牛啊牛啊
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4185 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 02:00 · PVG 10:00 · LAX 18:00 · JFK 21:00
    ♥ Do have faith in what you're doing.