Skip to main content
 首页 » 编程设计

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

2024年10月24日11kuangbin

当我运行下面的代码时

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) 

我收到错误:数据项“DemandValue”没有索引为 (PL1, P1) 的条目。

我想在条目不可用时获得零值并继续循环。与 iferror 在 excel 中的执行方式非常相似。

请您参考如下方法:

为 DemandValue 使用 collections.defaultdict。

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})