如何简化重复的Python-PuLP语法?

2024-10-01 15:48:53 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将以下Python-PuLP语句简化为更Python、可管理和更正确的语句:

import pulp as lp

#delare variables
#Note that I have to model a 100 year period!
year_1 = lp.LpVariable("2011", 0, None, lp.LpInteger)    
year_2 = lp.LpVariable("2012", 0, None, lp.LpInteger)
year_. = lp.LpVariable("201.", 0, None, lp.LpInteger)
year_n = lp.LpVariable("201n", 0, None, lp.LpInteger)

#declare constraints
prob += year_1 - year_0 >= 0
prob += year_2 - year_1 >= 0
prob += year_. - year_. >= 0
prob += year_n - year_n_1 >= 0

Tags: importnonethatas语句variablesyearpulp
1条回答
网友
1楼 · 发布于 2024-10-01 15:48:53

列出年份而不是100年的变量:

years = [lp.LpVariable(str(2011+i), 0, None, lp.LpInteger) for i in xrange(n)]

注意,列表是0索引的,所以以前是year_1的现在是{}。在

对于脚本的“declare constraints”部分,可以对其进行循环:

^{pr2}$

相关问题 更多 >

    热门问题