如何将纸浆决策变量的输出打印为矩阵格式

问题描述

我想将模型的解决方案导出为矩阵形式,因此将变量添加到Soln中,但要输入key error。请帮助解决此问题。

或建议使用其他方法将解决方案导出为m * n的表格式。

KeyError                                  Traceback (most recent call last)
<ipython-input-52-c86dd2a00da5> in <module>()
     82 for i in range (1,Box+1):
     83   for j in range (1,Pallet+1):
---> 84     Soln[i][j]=x[i][j]
     85 
     86 
KeyError: 1


from pulp import *
import numpy as np
Box=6
Pallet=6
Variable_range=Box*Pallet
x = {}

from pulp import LpMaximize,LpProblem,LpStatus,lpSum,LpVariable
# Define the model
model = LpProblem(name="Container Loading",sense=LpMaximize)

# Define the decision variables

#Decision variables X
for i in range(1,Box+1):
    for j in range (1,Pallet+1):
      x[(i,j)] = pulp.LpVariable('x' + str(i) + '_' + str(j),1,LpBinary)

# Add constraints

#constraint for restricting unique number of boxes based on orientation
for i in range (1,(Box//2)+1):
     for j in range (1,Pallet+1):
       model += x[(i*2-1,j)] + x[(i*2,j)] <= 1 

#print (model)
#Set the objective
model += lpSum(x.values())

# Solve the optimization problem
status = model.solve()

Soln= [[0]*Pallet]*Box
for i in range (1,Box+1):
  for j in range (1,Pallet+1):
    Soln[i][j]=x[i][j]  # Error in this line


print(Soln)

解决方法

Soln= np.zeros((Box,Pallet))
print (Soln[5][5])
for i in range (1,Box+1):
  for j in range (1,Pallet+1):
    value=x[(i,j)].value()
    Soln[i-1][j-1]=value

此修改给了我预期的输出

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...