当数据项中不存在元素时如何获得零值

时间:2015-08-07 11:09:39

标签: python

当我运行以下代码时

for (x,y) in [(x,y) for x in Sites for y in Products] : 

    prob += (SupplyValue[(x,y)] + lpSum([vars[(i,j,k)] for (i,j,k) in TP if j==x  and k==y]) >=
             DemandValue[(x,y)] + lpSum([vars[(i,j,k)] for (i,j,k) in TP if i==x and k==y])), "Product Flow:%s %s" %(x,y)

我收到错误:There is no entry with index(PL1, P1) for the data item "DemandValue".

每当条目不可用时我想获得零值并继续循环。就像iferror在excel中所做的一样。

2 个答案:

答案 0 :(得分:2)

collections.defaultdict使用DemandValue

In [1]: import collections

In [2]: DemandValue = collections.defaultdict(lambda: 0)

In [3]: DemandValue[0]
Out[3]: 0

In [4]: DemandValue[1]
Out[4]: 0

In [5]: DemandValue[0] = 12

In [6]: DemandValue[3] = 2

In [7]: DemandValue
Out[7]: defaultdict(<function <lambda> at 0x807ab0400>, {0: 12, 1: 0, 3: 2})

In [8]: DemandValue[7]
Out[8]: 0

更新:重新使用现有词典:

In [1]: import collections

In [2]: normal = {1: 'foo', 'test': 'bar', (3,4): 17}

In [3]: d = collections.defaultdict(lambda: 0, normal)

In [4]: d
Out[4]: defaultdict(<function <lambda> at 0x807a90f28>, {1: 'foo', 'test': 'bar', (3, 4): 17})

答案 1 :(得分:0)

try:
     prob += (SupplyValue[(x,y)] + lpSum([vars[(i,j,k)] for (i,j,k) in TP if j==x  and k==y]) >=
     DemandValue[(x,y)] + lpSum([vars[(i,j,k)] for (i,j,k) in TP if i==x and k==y])), "Product Flow:%s %s" %(x,y)
except:
     pass

你总是可以抓住错误,忽略它们;)

编辑:我听说,这是一个线性编程问题,你不想重新构建循环,在每个迭代步骤中添加一个try / except,我的建议需要这个,抱歉。

但是,我认为该方法适用..有点......:

def getDemandValue(x,y):
    try:
        return DemandValue[(x,y)]
    except:
        return 0

 prob += (SupplyValue[(x,y)] + lpSum([vars[(i,j,k)] for (i,j,k) in TP if j==x  and k==y]) >=
 getDemandValue[(x,y)] + lpSum([vars[(i,j,k)] for (i,j,k) in TP if i==x and k==y])), "Product Flow:%s %s" %(x,y)