英文:
Product of the Dictionary Values from Combinations of Dictionary Keys in Python
问题
我有一个Python中的字典集合:
dct = {'k1': {1, 2, 3, 4}, 'k2': {100, 200}, 'k3': {1000, 2000, 3000, 4000}, 'k4': {25, 50}}
我想找到所有可能的三个键组合的笛卡尔积,比如:
'k1', 'k2', 'k3' >> product({1, 2, 3, 4}, {100, 200}, {1000, 2000, 3000, 4000})
'k1', 'k2', 'k4' >> product({1, 2, 3, 4}, {100, 200}, {25, 50})
等等
我下面的代码可以工作,但似乎不够Pythonic,我想知道是否有更优雅的解决方案,也许可以使用 * 来展开字典。我的解决方案是针对三个组合的情况,一个通用的解决方案,可以处理n个组合,会更有趣...
for x, y, z in combinations(dct.keys(), 3):
for p in product(dct[x], dct[y], dct[z]):
英文:
I have a dictionary of sets in Python
dct={'k1':{1,2,3,4},'k2':{100,200},'k3':{1000,2000,3000,4000},'k4':{25,50}}
and I want to find the Cartesian product of all the possible combinations of, say 3 keys, so
'k1','k2','k3' >> product({1,2,3,4}, {100,200}, {1000,2000,3000,4000})
'k1','k2','k4'>> product({1,2,3,4}, {100,200}, {25,50})
etc
The code I’ve got below works, but doesn’t seem that pythonic and was wondering whether there was a more elegant solution, maybe using * to unpack the dictionary. My solution is fixed for 3 combinations, a general solution which could cater for n-combinations would be interesting...
for x,y,z in combinations(dct.keys(),3):
for p in product(dct[x],dct[y],dct[z]):
答案1
得分: 1
使用combinations
中的值。在调用product
时将返回值解包为一个元组。
from itertools import combinations, product
dct = {'k1': {1, 2, 3, 4}, 'k2': {100, 200}, 'k3': {1000, 2000, 3000, 4000},
'k4': {25, 50}}
for combi in combinations(dct.values(), 3):
for p in product(*combi):
print(p)
英文:
Use the values in combinations
. Get the return value in a tuple and unpack that tuple in the call to product
.
from itertools import combinations, product
dct = {'k1': {1, 2, 3, 4}, 'k2': {100, 200}, 'k3': {1000, 2000, 3000, 4000},
'k4': {25, 50}}
for combi in combinations(dct.values(), 3):
for p in product(*combi):
print(p)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论