[英]How to create combinations of key values in a dictionary?
我有以下代码工作:
from itertools import product
dict = { 'Orange' : [ 2,4,8],
'Banana' : [8,16,32]
}
names = list(dict.keys())
fruits ={}
offset =0
for combination in product ( *dict.values()):
fruits[f'set{offset}'] = [[names[0] ,combination[0]], [names[1],combination[1]]]
offset+=1;
print (fruits)
Output:
{'set0': [['Orange', 2], ['Banana', 8]],
'set1': [['Orange', 2], ['Banana', 16]],
'set2': [['Orange', 2], ['Banana', 32]],
'set3': [['Orange', 4], ['Banana', 8]],
'set4': [['Orange', 4], ['Banana', 16]],
'set5': [['Orange', 4], ['Banana', 32]],
'set6': [['Orange', 8], ['Banana', 8]],
'set7': [['Orange', 8], ['Banana', 16]],
'set8': [['Orange', 8], ['Banana', 32]]
}
现在,当我的字典增加到有更多的水果和更多的价值时。 我需要在 for 循环中手动处理它。 我该如何扩展它?
替换这个:
[[names[0] ,combination[0]], [names[1],combination[1]]]
使用zip
:
[[name, count] for name, count in zip(names, combination)]
这将允许它扩展到任何长度的列表,而无需指定每个索引。
从 pprint 导入 pprint 导入 itertools
d = {'Orange' : [ 2,4,8],
'Banana' : [8,16,32],
'pear': [9,7,5]
}
out = {}
for k,v in d.items():
# pprint(list(itertools.product([k],v)))
out[k] = itertools.product([k],v)
final = itertools.product(*out.values())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.