【问题标题】:Evaluate function with all combinations of arguments in dictionary使用字典中所有参数组合评估函数
【发布时间】:2021-12-08 10:03:56
【问题描述】:

我想为最多使用 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 可以工作,但我找不到转换字典的方法......

【问题讨论】:

    标签: python function dictionary arguments


    【解决方案1】:

    一种方法是使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 2018-08-01
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多