在Python中,字典键的组合的字典值的乘积。

huangapple go评论75阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年7月20日 16:06:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76727842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定