对所有可能的参数组合执行函数

2024-10-05 14:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组要作为参数应用于函数的值:

params = {
    'a': [1, 2, 3],
    'b': [5, 6, 7],
    'x': [None, 'eleven', 'f'],
    # et cetera
}

我想用所有可能的组合运行myfunc(),所以myfunc(a=1, b=5, x=None ...)myfunc(a=2, b=5, x=None ...)。。。myfunc(a=3, b=7, x='f' ...)。有什么东西(例如itertools)可以帮助你吗?我考虑过使用itertools.product(),但它没有保留参数的名称,只给了我组合的元组。在


Tags: 函数名称none参数paramsproductmyfuncet
2条回答

可以使用^{}获取参数的所有组合:

>>> import itertools
>>> for xs in itertools.product([1,2], [5,6], ['eleven', 'f']):
...     print(xs)
... 
(1, 5, 'eleven')
(1, 5, 'f')
(1, 6, 'eleven')
(1, 6, 'f')
(2, 5, 'eleven')
(2, 5, 'f')
(2, 6, 'eleven')
(2, 6, 'f')

使用Argument list unpacking,可以使用关键字参数的所有组合调用myfunc

^{pr2}$

输出:

{'a': 1, 'x': None, 'b': 5}
{'a': 1, 'x': None, 'b': 6}
{'a': 1, 'x': None, 'b': 7}
{'a': 1, 'x': 'eleven', 'b': 5}
{'a': 1, 'x': 'eleven', 'b': 6}
{'a': 1, 'x': 'eleven', 'b': 7}
{'a': 1, 'x': 'f', 'b': 5}
...

.keys.values的排序在所有Python版本中都得到了保证(除非dict被更改,而这在这里不会发生),因此这可能有点微不足道:

from itertools import product

for vals in product(*params.values()):
    myfunc(**dict(zip(params, vals)))

您可以在docs中找到担保:

If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.


演示

^{pr2}$
{'a': 1, 'x': None, 'b': 5}
{'a': 1, 'x': None, 'b': 6}
{'a': 1, 'x': None, 'b': 7}
{'a': 1, 'x': 'eleven', 'b': 5}
{'a': 1, 'x': 'eleven', 'b': 6}
{'a': 1, 'x': 'eleven', 'b': 7}
{'a': 1, 'x': 'f', 'b': 5}
{'a': 1, 'x': 'f', 'b': 6}
{'a': 1, 'x': 'f', 'b': 7}
...

相关问题 更多 >