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

时间:2017-07-03 14:08:50

标签: python function combinations

我想将一组值作为参数应用于函数:

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(),但这并没有保留参数的名称,只是给了我组合的元组。

3 个答案:

答案 0 :(得分:8)

您可以使用itertools.product获取所有参数组合:

>>> 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

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

def myfunc(**args):
    print(args)

import itertools
keys = list(params)
for values in itertools.product(*map(params.get, keys)):
    myfunc(**dict(zip(keys, values)))

输出:

{'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}
...

答案 1 :(得分:3)

所有Python版本中.keys.values的排序都是保证(除非dict被更改,但这里没有发生),所以这可能有点微不足道:< / p>

from itertools import product

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

您可以在docs

中找到保证
  

如果迭代了键,值和项视图而没有干预   修改字典,项目的顺序将直接   对应。

<强>演示

for vals in product(*params.values()):
    print(dict(zip(params, vals)))
{'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}
...

答案 2 :(得分:1)

我开发了combu就是这样的解决方案。

  1. 安装combu

pip install combu

  1. 使用combu
# Case 1: Directly call
import combu

for res, param in combu.execute(myfunc, params):
    print(res, params)

# Case 2: Use class
from combu import Combu

comb = Combu(myfunc)

for res, param in comb.execute(params):
    print(res, params)
相关问题