字典理解列表值

时间:2016-04-11 13:01:07

标签: python python-3.x list-comprehension dictionary-comprehension

我想知道是否有更多Pythonic方式来执行以下操作,可能使用字典理解:

A = some list
D = {}
for i,v in enumerate(A):
    if v in D:
        D[v].append(i)
    else:
        D[v] = [i]

2 个答案:

答案 0 :(得分:4)

使用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

答案 1 :(得分:1)

您可以执行以下操作

d = collections.defaultdict(list)
for i,v in enumerate(A):
    d[v].append(i)

您可以看到生成的字典的值为list s,其元素将在遍历时生成。如果你坚持做一个dict comp,你必须首先找到所有(value, [indices]),然后在[(k,[v])]上做一个dict comp,这意味着额外的杂技没有任何好处。