提问人:Guy 提问时间:7/20/2023 最后编辑:engGuy 更新时间:7/20/2023 访问量:30
Python 中字典键组合的字典值的乘积
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}}
我想找到所有可能组合的笛卡尔积,比如 3 个键,所以
'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
我下面的代码可以工作,但似乎不是那么 pythonic,并且想知道是否有更优雅的解决方案,也许使用 * 来解压缩字典。我的解决方案是固定的 3 种组合,一个可以满足 n 种组合的通用解决方案会很有趣......
for x,y,z in combinations(dct.keys(),3):
for p in product(dct[x],dct[y],dct[z]):
答:
1赞
Matthias
7/20/2023
#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)
评论
0赞
Guy
7/20/2023
谢谢你,我一直在磕磕绊绊,你让它变得如此简单!
评论