【发布时间】:2017-04-28 22:33:51
【问题描述】:
问题陈述
给定一个列表字典,
key_to_list = {
'one': [1, 3, 5, 7],
'two': [2, 4, 6, 8],
'three': [1, 2, 5, 6],
'four': [2, 5, 7, 8]
}
创建从列表元素到其键的映射的最佳方法是什么?
list_element_to_keys = {
1: {'one', 'three'},
2: {'two', 'three', 'four'},
3: {'one'},
4: {'two'},
5: {'one', 'three', 'four'},
6: {'two', 'three'},
7: {'one', 'four'},
8: {'two', 'four'}
}
我的解决方案
from collections import defaultdict
list_element_to_keys = defaultdict(set)
for key, value in key_to_list.items():
for item in value:
list_element_to_keys[item].add(key)
想法
我的一个朋友建议可以使用 字典理解,但我一直遇到问题 因为多个键的列表包含一些相同的项目。
我也认为他们可能是一些 itertools 的魔法,可以提供帮助,
但我并不积极。
听写理解
在朋友的帮助下,我发现了一种有效的字典理解。
from itertools import chain
list_element_to_keys= { i: set(k for k,v in key_to_list.items() if i in v) for i in set(chain.from_iterable(key_to_list.values())) }
【问题讨论】:
-
这属于codereview.stackexchange.com。无论如何,我认为您的解决方案很好,根本不需要更改。
标签: python dictionary list-comprehension itertools defaultdict