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