如何简化重复的Python PuLP语法?
作者:互联网
如何将以下Python PuLP语句简化为Pythonic,可管理和正确的内容:
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
解决方法:
列出年份而不是100年变量:
years = [lp.LpVariable(str(2011+i), 0, None, lp.LpInteger) for i in xrange(n)]
请注意,列表是0索引的,因此以前的year_1现在是年[0].
您可以循环遍历脚本的“声明约束”部分:
for year, next_year in zip(years[:-1], years[1:]):
prob += next_year - year >= 0
标签:python,linear-programming,pulp 来源: https://codeday.me/bug/20190620/1243055.html