Execute function for all possible combinations of parameters

I have sets of values ​​that I want to use as parameters for a function:

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

I want to run myfunc()with all possible combinations, so myfunc(a=1, b=5, x=None ...), myfunc(a=2, b=5, x=None ...)... myfunc(a=3, b=7, x='f' ...). Maybe something (for example, in itertools)? I was thinking about using itertools.product(), but this does not save the parameter names and just gives me tuples from the combinations.

+6
source share
2 answers

You can use itertools.productto get all combinations of arguments:

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

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}
...
+5

.keys .values Python ( dict, ), :

from itertools import product

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

gurantee docs:

, , .


Demo

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}
...
+3

All Articles