字典中的PuLP变量定义

问题描述 投票:0回答:1

我想用PuLP声明一组变量,其中包含以下列表的所有可能组合:

month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
manufacturer = ['China', 'Mexico', 'Taiwan']
demand = ['London', 'Paris', 'Milan']

然后,我将有一个字典(例如),如下所示:'1.China.London''1.China.Paris',...

我尝试使用以下代码,但是我不知道如何存储所有组合。

vlbs = {}
for key in month:
    for kay in manufacturer:
        for eyk in demand:
            vlbs = (str(key)+'.'+str(kay)+'.'+str(eyk))

首先,我没有正确获得字典vlbs。后来:

variables = {var: pl.LpVariable(var, lowBound = 0) for var in vlbs}

如何正确解决?

python loops dictionary pulp
1个回答
0
投票

您可以使用元组作为字典键。我认为,这比过滤一串字符串进行连接和拆分要容易得多。

months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
manufacturers = ['China', 'Mexico', 'Taiwan']
demands = ['London', 'Paris', 'Milan']

var_dict = {}

for month in months:
    for manufacturer in manufacturers:
        for demand in demands:
            combo = (month, manufacturer, demand)
            var_name = '.'.join([str(c) for c in combo])
            var_dict[combo] = LpVariable(var_name, lowBound=0) 

# add constraint for month 1
model += lpSum([k for k in var_dict if k[0] == 1]) <= 50

© www.soinside.com 2019 - 2024. All rights reserved.