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

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