![](/img/trans.png)
[英]Python - Check all the key - value pairs in a dict and convert to int or float
[英]Getting all combinations of key/value pairs in Python 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]}]
換句話說,無論順序如何,我都希望dict中兩個鍵/值對的所有組合無需替換。
一種解決方案是使用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)))
我更喜歡@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
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]}]
我相信這會得到你所需要的。
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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.