简体   繁体   English

纸浆中的循环 Python

[英]For loop in Pulp Python

I have a Pulp problem that is working fine and gives me the right values, but I want to clean up the code.我有一个 Pulp 问题,它运行良好并给了我正确的值,但我想清理代码。 Here is the part in question:这是有问题的部分:

prob += (select_vars['MeatA'] + select_vars['MeatB'] + select_vars['MeatC']) >= 3, ""

I want to put this into a for loop, like this:我想把它放到一个for循环中,像这样:

meat_count = 0
Meats = ["MeatA", "MeatB", "MeatC"]
for i in Meats:
    if select_vars[i] is not None: meat_count += 1
    prob += meat_count >= 5, "Meat min"

But that is putting NoneTypes into my prob.variables() and I'm not sure why.但这将 NoneTypes 放入我的 prob.variables() 中,我不知道为什么。 There are no NoneTypes in my prob.variables() when I run it the first way without the for loop.当我在没有 for 循环的情况下以第一种方式运行它时,我的 prob.variables() 中没有 NoneTypes。

# Print out the variables with their optimal value
for v in prob.variables():
    print("some none ", v)
    if v.varValue > 0:
        print(v.name, "=", v.varValue)

First of all, I recommend you check the Case Studies in the PuLP documentation.首先,我建议您查看 PuLP 文档中的案例研究 There, you will see how to use loops to make general models that adapt to your data.在那里,您将看到如何使用循环来制作适应您的数据的通用模型。 Also: I'm not sure you're making a difference between python variables and PuLP variables, which is important.另外:我不确定您是否在 python 变量和 PuLP 变量之间有所不同,这很重要。

In your case, you probably want to do something like the following:在您的情况下,您可能想要执行以下操作:

import pulp
prob = pulp.LpProblem('example')
Meats = ['MeatA', 'MeatB', 'MeatC']
select_vars = pulp.LpVariable.dicts("selected_vars", Meats)
prob += pulp.lpSum(select_vars.get(m, 0) for m in Meats) >= 3, ""

But I insist, check the examples to see what each constraint does.但我坚持要检查示例以查看每个约束的作用。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM