假设我有一个变量结构如下:
results = [([123], 456),
([1, 2, 3], 456),
([2], 456)]
我希望使用字典理解将其放入字典中,我实现了这样做:
{item[1]:set(i for item in results for i in item[0]) for item in results}
{456: {1, 2, 3, 123}}
但现在假设变量results
变为:
[([123], 456),
([1, 2, 3], 456),
([2], 456),
([789], 'fizz')]
我未能成功地改变理解以适应这种情况。如何通过使用字典理解来实现这一结果?我知道如何使用循环来完成它,但我希望通过理解来学习如何实现它。谢谢!
编辑:
输出如下:
{456: {1, 2, 3, 123}, 'fizz': {789}}
答案 0 :(得分:4)
You can easily do this without a comprehension, but if you insist on a comprehension, here's a solution that uses itertools.groupby
:
from itertools import groupby
import operator
f = operator.itemgetter(1)
r = {k: set(i for x in g for i in x[0]) for k, g in groupby(results, f)}
print(r)
# {456: set([3, 1, 2, 123]), 'fizz': set([789])}
Caveat: Note that no presorting is done, since the items are already arranged according to the group key.
The solution is more readable (say more Pythonic) with a simple for loop that uses defaultdict
:
from collections import defaultdict
r = defaultdict(set)
for v, k in results:
r[k].update(v)
print(r)
# defaultdict(<type 'set'>, {456: set([3, 1, 2, 123]), 'fizz': set([789])})
答案 1 :(得分:1)
Here is a solution using only dictionary and set comprehension:
{b: {k for x, y in results for k in x if y == b} for a, b in results}