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