查找Python中所有可能的参数组合 [英] Find all possible combinations of arguments in Python
问题描述
我有一个具有以下签名的函数:
I have a function that has a following signature:
def function(a=None, b=None, c=None):
# ... some more code ...
如果通过,则,b和c只能是布尔值。
If passed, a, b and c can only be booleans.
我想知道a,b和c的所有有效组合。
I want to know all the valid combinations of a, b and c.
请注意,a,b和c是可选的,因此可以使用最少0个参数和最多3个参数来调用此函数。
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)
)
哪个会产生:
[('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
哪个产生:
[('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)]
绝对错误的路径。
推荐答案
如果每个值都可以保存 None
, False
或 True
产生这些组合(使用 itertools.product()
,并过滤掉选择了无
的元素:
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
这将产生:
>>> 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}
这篇关于查找Python中所有可能的参数组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!