有关具有唯一值的元组列表,例如:
a = [(1, 2), (3, 4), (5, 6)]
我想创建一张地图:
b = {}
for t in a:
for tt in t:
b[tt] = t
>>> {1: (1, 2), 2: (1, 2), 3: (3, 4), 4: (3, 4), 5: (5, 6), 6: (5, 6)}
如果没有明确的for循环,是否有更好/更方便的方法来实现这一目标?一种方法可能是使用dict.update
,尽管这可能会让元组中的许多项目变得丑陋:
[(b.update({t1: (t1, t2)}), b.update({t2: (t1, t2)})) for t1, t2 in a]
答案 0 :(得分:4)
使用词典理解:
>>> a = [(1, 2), (3, 4), (5, 6)]
>>> {i: tup for tup in a for i in tup}
{1: (1, 2), 2: (1, 2), 3: (3, 4), 4: (3, 4), 5: (5, 6), 6: (5, 6)}
答案 1 :(得分:2)
from itertools import chain
flatten = chain.from_iterable
a = [(1, 2), (3, 4), (5, 6)]
d = dict(flatten(((k, (k, v)), (v, (k, v))) for k, v in a))
print(d)
答案 2 :(得分:0)
字典理解:
{**{k: (k, v) for k, v in a}, **{v: (k, v) for k, v in a}}