Find all possible combinations of arguments in Python

时光毁灭记忆、已成空白 提交于 2020-01-14 05:18:46

问题


I have a function that has a following signature:

def function(a=None, b=None, c=None):
    # ... some more code ... 

If passed, a, b and c can only be booleans.

I want to know all the valid combinations of a, b and c.

Note that a, b and c are optional, so this function can be called with as little as 0 parameters and as much as 3 parameters.

I'm able to get all the possible argument combinations:

arg_names = ['a', 'b', 'c']
arg_values = [None, True, False]

arg_combinations = []
for i in range(len(arg_names)):
    arg_combinations += list(
        itertools.combinations(arg_names, i + 1)
    )

Which produces:

[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]

However I'm not able to move further, creating all possible combinations of parameters and values:

arg_value_combinations = []
for c in arg_combinations:
    arg_value_combinations += list(
        itertools.product(c, arg_values)
    )

print arg_value_combinations

Which produces:

[('a', None), ('a', True), ('a', False), ('b', None), ('b', True), ('b', False), ('c', None), ('c', True), ('c', False), ('a', None), ('a', True), ('a', False), ('b', None), ('b', True), ('b', False), ('a', None), ('a', True), ('a', False), ('c', None), ('c', True), ('c', False), ('b', None), ('b', True), ('b', False), ('c', None), ('c', True), ('c', False), ('a', None), ('a', True), ('a', False), ('b', None), ('b', True), ('b', False), ('c', None), ('c', True), ('c', False)]

Definitely wrong path.


回答1:


If each value can hold None, False or True, simply produce those combinations (with itertools.product() , and filter out the elements that picked None:

from itertools import product

for combo in product((None, True, False), repeat=3):
    arguments = {k: v for k, v in zip('abc', combo) if v is not None}
    print arguments

This produces:

>>> from itertools import product
>>> for combo in product((None, True, False), repeat=3):
...     arguments = {k: v for k, v in zip('abc', combo) if v is not None}
...     print arguments
... 
{}
{'c': True}
{'c': False}
{'b': True}
{'c': True, 'b': True}
{'c': False, 'b': True}
{'b': False}
{'c': True, 'b': False}
{'c': False, 'b': False}
{'a': True}
{'a': True, 'c': True}
{'a': True, 'c': False}
{'a': True, 'b': True}
{'a': True, 'c': True, 'b': True}
{'a': True, 'c': False, 'b': True}
{'a': True, 'b': False}
{'a': True, 'c': True, 'b': False}
{'a': True, 'c': False, 'b': False}
{'a': False}
{'a': False, 'c': True}
{'a': False, 'c': False}
{'a': False, 'b': True}
{'a': False, 'c': True, 'b': True}
{'a': False, 'c': False, 'b': True}
{'a': False, 'b': False}
{'a': False, 'c': True, 'b': False}
{'a': False, 'c': False, 'b': False}


来源:https://stackoverflow.com/questions/26000389/find-all-possible-combinations-of-arguments-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!