从字典键

时间:2018-04-20 03:58:27

标签: dictionary parameters pyomo

我是Python / Pyomo的新手,我正在尝试从我创建的这个词典中的键('score')定义一个参数cost(n):

operations[1] = {"score" : 100, "start_node": 2, "end_node": 3}
operations[2] = {"score" : 120, "start_node": 4, "end_node": 3}
...
operations[n] = {"score" : 155, "start_node": 5, "end_node": 2}

我试图用这种方法做到这一点,但它似乎不起作用:

n_operations=len(operations) 
model = ConcreteModel()
model.O = RangeSet(1,n_operations)

def c_init(model, operations):

   for i in range(1,n_operations):
       print(i)
       cost=operations[i]['score']
       return cost

model.cost = Param(model.O, initialize=c_init)

您是否了解如何解决此问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

与Pyomo中的所有规则一样,当您将函数传递给Param的initialize=关键字时,该函数对于每个索引都称为一次。因此,您应该将规则修改为:

def c_init(model, operation):
    return operations[operation]['score']