使用 defaultdict
:
from collections import defaultdict
D = defaultdict(list)
[D[v].append(i) for i, v in enumerate(A)]
使用setdefault
:
D = {}
[D.setdefault(v, []).append(i) for i, v in enumerate(A)]
我无法想到任何使用字典推导而不对数据进行排序的方法:
from itertools import groupby
from operator import itemgetter
{v: ids for v, ids in groupby(enumerate(sorted(A)), itemgetter(1))}
表演:
from collections import defaultdict
from itertools import groupby
from operator import itemgetter
from random import randint
A = tuple(randint(0, 100) for _ in range(1000))
def one():
D = defaultdict(list)
[D[v].append(i) for i, v in enumerate(A)]
def two():
D = {}
[D.setdefault(v, []).append(i) for i, v in enumerate(A)]
def three():
{v: ids for v, ids in groupby(enumerate(sorted(A)), itemgetter(1))}
from timeit import timeit
for func in (one, two, three):
print(func.__name__ + ':', timeit(func, number=1000))
结果(一如既往,最简单的获胜):
one: 0.25547646999984863
two: 0.3754340969971963
three: 0.5032370890003222
map
,但列表推导式更易读,并且通常更受欢迎。参考链接:https://dev59.com/mHM_5IYBdhLWcg3wvV5w#1247490 和 http://www.u.arizona.edu/~erdmann/mse350/topics/list_comprehensions.html。 - aluriak