[英]Python code went wrong for my optimization problem
I am new in using python.我是使用 python 的新手。 I tried to write a code for my optimization research model.
我尝试为我的优化研究 model 编写代码。 Could you help me please?
请问你能帮帮我吗? I don't know what's wrong with the code.
我不知道代码有什么问题。 I am using python 2 by the way.
顺便说一句,我正在使用 python 2。 Thank you.
谢谢你。
for i in range(len(lift)):
prob+=lpSum(dec_var[i])<=1
#constraints
col_con=[1,0,0,2,2,3,1,1]
dec_var=np.array(dec_var)
col_data=[]
for j in range(len(brands)):
col_data.append(list(zip(*dec_var)[j]))
prob+=lpSum(col_data[j])<=col_con[j]
#problem
prob.writeLP("SO.lp")
#solve the problem
prob.solve()
print("The maximum Total lift obtained is:",value(prob.objective)) # print the output
#print the decision variable output matrix
Matrix=[[0 for X in range(len(lift[0]))] for y in range(len(lift))]
for v in prob.variables():
Matrix[int(v.name.split("_")[2])][int(v.name.split("_")[3])]=v.varValue
matrix=np.int_(Matrix)
print ("The decision variable matrix is:")
print(matrix)
TypeError Traceback (most recent call last) in 13 for j in range(len(brands)): 14 ---> 15 col_data.append(list(zip(*dec_var)[j])) 16 17 prob+=lpSum(col_data[j])<=col_con[j]
TypeError Traceback(最近一次调用最后一次)在 13 for j in range(len(brands)): 14 ---> 15 col_data.append(list(zip(*dec_var)[j])) 16 17 prob+=lpSum(col_data [j])<=col_con[j]
TypeError: 'zip' object is not subscriptable
TypeError: 'zip' object 不可下标
Your code breaks in this line:您的代码在这一行中断:
col_data.append(list(zip(*dec_var)[j]))
Lets go through it step by step: dec_var is an array, probably with multiple dimensions.让 go 一步一步来: dec_var 是一个数组,可能有多个维度。 Something like this:
像这样的东西:
dec_var=np.array([[1,2,3,4],[5,6,7,8]])
dec_var
#array([[1, 2, 3, 4],
# [5, 6, 7, 8]])
The star operator (*) breaks the array into 'variables'.星号运算符 (*) 将数组分解为“变量”。 Something more or less like this: a = [1,2,3,4], b = [5,6,7,8].
或多或少像这样:a = [1,2,3,4],b = [5,6,7,8]。 ('a' and 'b' don't really exist, just trying to paint a picture).
('a' 和 'b' 并不真正存在,只是想画一幅画)。
Next, you apply zip(), which allows you to iterate two iterables together.接下来,您应用 zip(),它允许您一起迭代两个可迭代对象。 You would usually use it like this:
你通常会这样使用它:
for i,j in zip([1,2],[3,4]):
print(i,j)
#1,3
#2,4
However, zip itself is not subscriptable, that is the error you are getting.但是, zip 本身不可下标,这就是您遇到的错误。
To make it subscriptable, you can apply list on it.要使其可下标,您可以在其上应用列表。
list(zip([1,2],[3,4]))[0]
#(1,3)
In other words.. The solution to your problem most likely is changing the position of the [j] subscript:换句话说..您的问题的解决方案很可能是更改 [j] 下标的 position:
From:从:
col_data.append(list(zip(*dec_var)[j]))
To:至:
col_data.append(list(zip(*dec_var))[j])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.