8

这可能是一个愚蠢的问题,但鉴于以下 dict:

combination_dict = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}

我将如何实现此列表:

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]}]

换句话说,我希望字典中两个键/值对的所有组合都没有替换,而不管顺序如何。

4

4 回答 4

20

一种解决方案是使用itertools.combinations()

result_list = map(dict, itertools.combinations(
    combination_dict.iteritems(), 2))

编辑:由于大众需求,这里有一个 Python 3.x 版本:

result_list = list(map(dict, itertools.combinations(
    combination_dict.items(), 2)))
于 2012-08-10T16:21:28.877 回答
1

我更喜欢@JollyJumper 的解决方案以提高可读性,尽管这个解决方案执行得更快

>>> from itertools import combinations
>>> d = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}
>>> [{j: d[j] for j in i} for i in combinations(d, 2)]
[{'three': [3, 4, 5], 'two': [2, 3, 4]}, {'three': [3, 4, 5], 'one': [1, 2, 3]}, {'two': [2, 3, 4], 'one': [1, 2, 3]}]

时间:

>python -m timeit -s "d = {'three': [3, 4, 5], 'two': [2, 3, 4], 'one': [1, 2, 3]}; from itertools import combinations" "map(dict, combinations(d.iteritems(), 2))"
100000 loops, best of 3: 3.27 usec per loop

>python -m timeit -s "d = {'three': [3, 4, 5], 'two': [2, 3, 4], 'one': [1, 2, 3]}; from itertools import combinations" "[{j: d[j] for j in i} for i in combinations(d, 2)]"
1000000 loops, best of 3: 1.92 usec per loop
于 2012-08-10T16:24:22.700 回答
0
from itertools import combinations
combination_dict = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}
lis=[]
for i in range(1,len(combination_dict)):
    for x in combinations(combination_dict,i):
        dic={z:combination_dict[z] for z in x}
        lis.append(dic)
print lis            

输出:

[{'three': [3, 4, 5]}, {'two': [2, 3, 4]}, {'one': [1, 2, 3]}, {'three': [3, 4, 5], 'two': [2, 3, 4]}, {'three': [3, 4, 5], 'one': [1, 2, 3]}, {'two': [2, 3, 4], 'one': [1, 2, 3]}]
于 2012-08-10T16:27:09.107 回答
-2

我相信这会给你你所需要的。

result list = [{combination_dict['one','two'],combination_dict['one','three']}]

我发现本教程非常有帮助:

http://bdhacker.wordpress.com/2010/02/27/python-tutorial-dictionaries-key-value-pair-maps-basics/

于 2012-08-10T16:29:38.010 回答