[英]Dictionary Comprehension for list values
I want to know if there's a more Pythonic way of doing the following, perhaps using dictionary comprehensions: 我想知道是否有更多Pythonic方式来执行以下操作,可能使用字典理解:
A = some list
D = {}
for i,v in enumerate(A):
if v in D:
D[v].append(i)
else:
D[v] = [i]
Using defaultdict
: 使用
defaultdict
:
from collections import defaultdict
D = defaultdict(list)
[D[v].append(i) for i, v in enumerate(A)]
Using setdefault
: 使用
setdefault
:
D = {}
[D.setdefault(v, []).append(i) for i, v in enumerate(A)]
I can't figure any mean to use a dictionnary comprehension without sorting the data: 在没有对数据进行排序的情况下,我无法理解使用字典理解:
from itertools import groupby
from operator import itemgetter
{v: ids for v, ids in groupby(enumerate(sorted(A)), itemgetter(1))}
Performances: 性能:
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))
Results (as always, the simplest win): 结果(一如既往,最简单的胜利):
one: 0.25547646999984863
two: 0.3754340969971963
three: 0.5032370890003222
You can do the following 您可以执行以下操作
d = collections.defaultdict(list)
for i,v in enumerate(A):
d[v].append(i)
You can see that the values of the resulting dictionary are list
s, the elements of which are to be produced while traversing. 您可以看到生成的字典的值是
list
s,其中的元素将在遍历时生成。 If you insist on doing a dict comp, you have to first find all the (value, [indices])
, then do a dict comp on [(k,[v])]
, which just means extra acrobatics without any benefit. 如果你坚持做一个dict comp,你必须首先找到所有的
(value, [indices])
,然后在[(k,[v])]
上做一个dict comp,这就意味着没有任何好处的额外杂技。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.