最近发现 defaultdict 的一个奇技淫巧 - 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 Guide
Contextualist
V2EX    Python

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

  •  
  •   Contextualist
    Contextualist 2021-03-07 00:10:22 +08:00 3229 次点击
    这是一个创建于 1679 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    倒是线程安全? asyncio 之类的协程非抢占式调度倒是没问题,抢占式的线程恐怕会造成问题。
    Contextualist
        14
    Contextualist  
    OP
       2021-03-08 14:03:50 +08:00
    @no1xsyzy 好观点。查了一下,这样(在 CPython 中)似乎的确不是线程安全的,因为如果工厂函数是 Python 代码,调用它的这个动作就是一个线程切换点。详见 https://stackoverflow.com/a/17682555,按照这个回答的提示,或许下面这个不优雅写法能行?
    ind = defaultdict()
    ind.default_factory = ind.__len__
    vegetableChick
        15
    vegetableChick  
       2021-03-09 17:19:40 +08:00
    牛啊牛啊
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     1036 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 22ms UTC 18:26 PVG 02:26 LAX 11:26 JFK 14:26
    Do have faith in what you're doing.
    ubao 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