Python:地图元组的组合 [英] Python: combinations of map tuples
问题描述
我在Python中有一个地图列表,如下所示:
I have a list of maps in Python looking like this:
2: a, b
3: b, c, d
4: a
我想创建键值对的所有组合,即:
And I want to create all conbinations of key-value-pairs, i.e.:
(2,a)(3,b)(4,a)
(2,a)(3,c)(4,a)
(2,a)(3,d)(4,a)
(2,b)(3,b)(4,a)
(2,b)(3,c)(4,a)
(2,b)(3,d)(4,a)
我既不知道地图的大小也不知道列表的大小,但是列表永远不会有超过4个元素.我可以假设键是唯一的,但不能假设它们始终是1,2,3,4或0,1,2,3,如上例所示.
I neither know the size of the maps nor the size of the list, but the list will never have more than 4 elements. I can assume that the keys are unique but not that they are always 1,2,3,4 or 0,1,2,3 as depicted in the example above.
解决这个问题的最聪明/最有效的方法是什么?
What is the smartest/most efficient way to solve this?
推荐答案
假定您的词典列表"采用此格式{2: ["a", "b"], 3: ["b", "c", "d"], 4: ["a"]}
(已确认 itertools.product
以获得这些对的组合.
Assuming that you "list of dict" is in this form {2: ["a", "b"], 3: ["b", "c", "d"], 4: ["a"]}
(as confirmed in comments), you can first use a list comprehension to get all the possible key-value pairs, and then just use itertools.product
to get the combinations of those pairs.
>>> d = {2: ["a", "b"], 3: ["b", "c", "d"], 4: ["a"]}
>>> pairs = [[(k, v) for v in d[k]] for k in d]
>>> list(itertools.product(*pairs))
[((2, 'a'), (3, 'b'), (4, 'a')),
((2, 'a'), (3, 'c'), (4, 'a')),
((2, 'a'), (3, 'd'), (4, 'a')),
((2, 'b'), (3, 'b'), (4, 'a')),
((2, 'b'), (3, 'c'), (4, 'a')),
((2, 'b'), (3, 'd'), (4, 'a'))]
使用实际"示例:
>>> d = {(8, 5): set(['Mt Everest', 'Mt Blanc']), (11, 5): set(['K2'])}
>>> pairs = [[(k, v) for v in d[k]] for k in d]
>>> list(itertools.product(*pairs))
[(((8, 5), 'Mt Everest'), ((11, 5), 'K2')),
(((8, 5), 'Mt Blanc'), ((11, 5), 'K2'))]
这篇关于Python:地图元组的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!