简体   繁体   English

如何在python中为所有可能的参数组合编写递归函数

[英]How to write a recursion function for all the possible parameter combinations in python

I am trying to write a piece of code to traverse all the possible parameter combinations for a algorithm with python. 我正在尝试编写一段代码来遍历python算法的所有可能参数组合。

import numpy as np
parameter={'alpha1':np.linspace(0.3,0.4,10),'alpha2':np.linspace(0.9,2,100),...'alpha5':np.linspace(5,10,100)}

the problem is that I just couldn't write 5-nested for loop.Can anyone give a demo on how to write a recursion function to give a list of all possible combinations of the parameters? 问题是我无法编写5嵌套的for循环。谁能给出一个演示如何编写递归函数以给出所有可能参数组合的列表的演示吗? Thanks 谢谢

You could use the itertools.product function, which takes a list of iterators and creates the iterator of their cartesian product (see documentation ). 您可以使用itertools.product函数,该函数获取一个迭代器列表并创建其笛卡尔乘积的迭代器(请参阅文档 )。

In my solution I use the values from the parameter dictionary as the iterators. 在我的解决方案中,我将parameter字典中的值用作迭代器。 I go over the product of the options for each key ( for values_option in product(*parameter.values()) ) and create a new dictionary with the original keys) 我遍历了每个键的选项乘积( for values_option in product(*parameter.values()) ),并使用原始键创建了一个新的字典)

from itertools import product
import numpy as np

parameter={'alpha1':np.linspace(0.3,0.4,10),'alpha2':np.linspace(0.9,2,100)}

def parameter_options(parameter):
    for values_option in product(*parameter.values()):
        yield dict(zip(parameter.keys(), values_option))

for opt in parameter_options(parameter):
    print opt

Let's go over this piece by piece: 让我们一步一步地看一下:

parameter.values()

This gives a list of the values for each key-value in the dictionary. 这给出了字典中每个键值的值列表。

For example, if we have dictionary = {a: (1, 2, 3), b: (4, 5, 6)} , using dictionary.values() will return [(1, 2, 3), (4, 5, 6)] . 例如,如果我们有dictionary = {a: (1, 2, 3), b: (4, 5, 6)} ,则使用dictionary.values()将返回[(1, 2, 3), (4, 5, 6)] Doing dictionary.keys() will give ['a', 'b'] . 进行dictionary.keys()将得到['a', 'b']

Note : There's a difference here between Python 2 and Python 3 - in Python 2 these methods ( keys() and values() ) will return normal lists, whereas in Python 3 they return a special iterator. 注意 :Python 2和Python 3之间有区别-在Python 2中,这些方法( keys()values() )将返回普通列表,而在Python 3中,它们将返回特殊的迭代器。 This shouldn't change the solution. 这不应该改变解决方案。

product(*parameter.values())

We use the asterisk to "unpack" lists. 我们使用星号“解压缩”列表。 Simply put, itertools.product receives any number of arguments. 简而言之, itertools.product接收任意数量的参数。 We want to use all the values as input: 我们要使用所有values作为输入:

vals = parameter.values()
product(vals[0], vals[1], vals[2], ..., vals[len(vals)])

Python has an easy way to pass lists as input to functions that receive an arbitrary number of arguments. Python有一种简单的方法将列表作为输入传递给接收任意数量参数的函数。 This last line is the same as product(*vals) . 最后一行与product(*vals)

for values_option in product(*parameter.values()):

We go over all the options for the values of the parameter dictionary. 我们遍历了parameter字典值的所有选项。

The first iteration will give the first option for all arguments. 第一次迭代将为所有参数提供第一个选项。 The second iteration will give the first option for all but one argument, which will have its second option. 第二个迭代将为除一个参数以外的所有参数提供第一个选项,该参数将具有第二个选项。 This goes on all the way until we have the last option where each argument has its last option. 这一直持续到我们有了最后一个选项,其中每个参数都有其最后一个选项。

zip(parameter.keys(), values_option)

This takes the two lists (of keys and possible values) and basically transposes them. 这将获取两个列表(包含键和可能的值),并从根本上转置它们。 it gives a list of the same length which includes pairs: the first element from the first list and the second from the second list. 它给出了一个长度相同的列表,其中包括成对的:第一个列表中的第一个元素和第二个列表中的第二个元素。 Like so: 像这样:

keys = ['a', 'b', 'c', 'd']
vals = [1, 2, 3, 4]
zip(keys, vals) = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

dict(...)

Now we can use this zipped list to create a dictionary. 现在,我们可以使用此压缩列表来创建字典。 This is a different way to initiate a dict 这是发起命令的另一种方式

{'a': 1, 'b': 2, 'c': 3} == dict([('a', 1), ('b', 2), ('c', 3)])

yield ...

This is what we use in python to create iterators. 这就是我们在python中用来创建迭代器的功能。 It's a complicated subject but instead of this you could write before the for loop this line 这是一个复杂的主题,但是您可以在for循环之前编写此行

options = []

and instead of yield dict(...) write options.append(dict(...)) . 而不是yield dict(...)编写options.append(dict(...)) and in the end of the function return options . 并且在函数的最后return options

Voila.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python中的所有可能组合(带有一个固定参数)? - All possible combinations in python (with one fixed parameter)? python-获得所有可能的组合与替换而无需递归 - python - get all possible combinations with replacement without recursion python 中所有可能的组合 - All possible combinations in python 如何获得元组的所有可能组合(python) - How to get all possible combinations of a tuple (python) 如何在 Python 中找到范围的所有可能组合? - How to find all the possible combinations of a range in Python? 如何在Python中制作单词的所有可能组合 - How to make all possible combinations of a word in Python 试图在 Python 中写出所有可能的 4 个字符组合的列表 - trying to write a list of all possible 4 characters combinations in Python 在Django中,如何编写查询以选择四个整数的所有可能组合? - In django, how to write a query that selects all possible combinations of four integers? Python,递归:给出满足布尔表达式的所有可能的元组组合 - Python, recursion : give all possible tuple combinations who meet a boolean expression (Python 递归)从 *args(包含字符串的列表列表)中获取所有可能的字符串组合: - (Python recursion) Getting all possible string combinations from *args(list of lists that contain strings):
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM