使用字典中参数的所有组合评估函数

Evaluate function with all combinations of arguments in dictionary

我想使用 numpy 包为最多在字典中给出的所有可能的参数组合(可能不同的数量)评估一个函数。

args1 = {'a' : [1, 2, 3], 'b' : [6, 7]}
args2 = {'a' : [1, 2, 3], 'b' : [6, 7], 'c' : [5, 4}


def fun(a, b, c = 1):
    return a + b + c

# What I want to automate:
fun(args1['a'][0], args1['b'][0])
fun(args1['a'][1], args1['b'][0])
.
.
.
fun(args2['a'][2], args2['b'][1], args2['c'][0])
fun(args2['a'][2], args2['b'][1], args2['c'][1])

有什么优雅的方法吗?我正在考虑将 'args' 转换为所有字典组合的列表(无法理解如何做到这一点......也许有字典理解?),然后使用 map()。或者 np.frompyfunc 可以工作,但我找不到转换字典的方法...

一种方法是使用 itertools.product 生成 组合

from itertools import product

args1 = {'a': [1, 2, 3], 'b': [6, 7]}
args2 = {'a': [1, 2, 3], 'b': [6, 7], 'c': [5, 4]}


def fun(a, b, c=1):
    return a + b + c


for pair in product(*args1.values()):
    res = fun(**dict(zip(args1, pair)))
    print(res)

输出

8
9
9
10
10
11

或者作为替代方案,只要字典的键与参数的(插入)顺序相同:

for pair in product(*args1.values()):
    res = fun(*pair)
    print(res)