And*_*w C 4 python combinations dictionary list
这可能是一个愚蠢的问题,但考虑到以下条款:
combination_dict = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}
Run Code Online (Sandbox Code Playgroud)
我将如何实现此列表:
result_list = [{"one": [1, 2, 3], "two": [2, 3, 4]}, {"one": [1, 2, 3], "three": [3, 4, 5]}, {"two": [2, 3, 4], "three": [3, 4, 5]}]
Run Code Online (Sandbox Code Playgroud)
换句话说,无论顺序如何,我都希望dict中的两个键/值对的所有组合无需替换.
Jol*_*per 14
一种解决方案是使用itertools.combinations():
result_list = map(dict, itertools.combinations(
combination_dict.iteritems(), 2))
Run Code Online (Sandbox Code Playgroud)
编辑:由于受欢迎的需求,这里有一个Python 3.x版本:
result_list = list(map(dict, itertools.combinations(
combination_dict.items(), 2)))
Run Code Online (Sandbox Code Playgroud)