Python笛卡尔积和条件? [英] Python cartesian product and conditions?

查看:71
本文介绍了Python笛卡尔积和条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我正在使用itertools.product()函数生成用于模拟的输入参数.

In Python I am using the itertools.product() function to generate input parameters for a simulation.

我有一个测试功能,需要4个输入参数a1,a2,b1和b2.我使用以下代码生成参数.示例:

I have a test function that requires 4 input parameters a1, a2, b1 and b2. I use the following code generate the parameters. Example:

params = itertools.product(range(10,41,2), range(10,41,2), range(0, 2), range(5, 31, 5))

…给了我3072种组合.不幸的是,某些组合在逻辑上是没有意义的.例如如果a2大于a1,则测试结果是无用的,而且当b1等于0时,b2的值也就完全无关紧要了,因此测试这种组合是没有意义的.

… which gives me 3072 combinations. Unfortunately some combinations logically make no sense. E. g. if a2 is larger than a1 the test results are useless, also when b1 equals 0 the value of b2 is completely irrelevant – so it wouldn’t make sense to test such combinations.

除了手动执行和嵌套for循环外,是否有可能限制或过滤笛卡尔积?因为我的实际用例具有4个以上的参数,所以这就是为什么我喜欢itertools提供的笛卡尔乘积函数的便利性.

Is there a possibility to restrict or filter the cartesian product beside doing it manually and nesting for-loops? Because my real use case has way more than 4 parameters, that’s why I like the convenience of the cartesian product function from itertools.

有什么想法或替代方法吗? 任何帮助表示感谢,谢谢.

Any ideas or alternatives? Any help appreciated, thanks.

推荐答案

如果您有很多参数,可以使用

If you have many parameters, a constraint-based approach using a module like python-constraint may be easier to work with - let it do the hard work of figuring out which combinations are valid.

这看起来像

from constraint import Problem

prob = Problem()
prob.addVariables(["a1", "a2"], range(10,41,2))
prob.addVariable("b1", [0, 2])
prob.addVariable("b2", range(5, 31, 5))
prob.addConstraint(lambda a1, a2: a2 <= a1, ["a1", "a2"])
prob.addConstraint(lambda b1, b2: b1 != 0 or b2 == 5, ["b1", "b2"])

for params in prob.getSolutionIter():
    run_sim(**params)

这篇关于Python笛卡尔积和条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆