配合自身 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
![]() | 1 ClericPy 2021-03-07 00:52:50 +08:00 有意思, 用的跟个 Enum 似的 |
![]() | 2 aijam 2021-03-07 08:36:46 +08:00 点赞 |
3 shutongxinq 2021-03-07 09:15:57 +08:00 有意思,赞! |
4 iConnect 2021-03-07 10:00:23 +08:00 via Android 赶紧想想,有哪些使用场景,性能好不好? |
![]() | 5 laoyuan 2021-03-07 10:22:38 +08:00 性能,性能是关键 |
![]() | 6 24bit 2021-03-07 10:39:21 +08:00 有意思 |
7 Contextualist OP |
![]() | 8 abersheeran 2021-03-07 12:17:17 +08:00 很有趣。 |
![]() | 9 abersheeran 2021-03-07 12:18:09 +08:00 |
![]() | 10 jokeface 2021-03-07 14:47:30 +08:00 为什么不会报错,感觉 ind 这个变量应该没有哇 |
12 xiaolinjia 2021-03-08 11:03:00 +08:00 在 py37 的 dict 有序后,这样就能按插入顺序取到索引吧。不过这个得先转 list 性能较差。 >>> a = {'a': 'aaa', 'b': 'bbb'} >>> list(a).index('a') 0 |
![]() | 13 no1xsyzy 2021-03-08 12:56:50 +08:00 |
14 Contextualist OP @no1xsyzy 好观点。查了一下,这样(在 CPython 中)似乎的确不是线程安全的,因为如果工厂函数是 Python 代码,调用它的这个动作就是一个线程切换点。详见 https://stackoverflow.com/a/17682555,按照这个回答的提示,或许下面这个不优雅写法能行? ind = defaultdict() ind.default_factory = ind.__len__ |
![]() | 15 vegetableChick 2021-03-09 17:19:40 +08:00 牛啊牛啊 |