这是我几天前问过的一个跟进问题。此时,我在尝试使用SQLITE在Python中生成字典时遇到以下错误:
'Traceback (most recent call last):
File "transportation problem.py", line 20, in <module>
I = set([i for (i,k) in d])
ValueError: too many values to unpack
这可以解决,这要归功于Andy Hayden最初提出的建议,但是当我将其实现到我的代码中时,我开始收到以下错误:
c[i,j,k] = cost[i,j] * weight[k]
KeyError: ((1, 2), 1)
我不确定是什么导致了这个错误,但是如果有人能指出我正确的方向,我会很高兴我能够如何使这个代码工作。我的代码如下所示:
#DISTANCE
cur.execute('SELECT idcustomer,idproduct,demand FROM demand')
result = cur.fetchall()
for idcustomer,idproduct,demand in result:
d[idcustomer,idproduct] = demand
I = set([i for (i,k) in d.iteritems()])
K = set([k for (i,k) in d.iteritems()])
#CAPACITY
cur.execute('select idfactory,capacity from factory')
result = cur.fetchall()
J, M = multidict(result)
produce = {1:[2,4], 2:[1,2,3], 3:[2,3,4]}
#WEIGHT
cur.execute('SELECT idproduct,weight FROM product')
result = cur.fetchall()
K, weight = multidict(result)
#COST
cur.execute('SELECT idcustomer,idfactory,distance FROM distance')
result = cur.fetchall()
for idcustomer,idfactory,distance in result:
cost[idcustomer,idfactory] = distance
c = {}
for i in I:
for j in J:
for k in produce[j]:
c[i,j,k] = cost[i,j] * weight[k]
错误发生在此代码的最后一行。当我手动输入SQLITE数据并将'd.iteritems'恢复为'd'时,代码可以正常工作。
produce = {1:[2,4], 2:[1,2,3], 3:[2,3,4]}
K, weight = multidict({1:5, 2:2, 3:3, 4:4})
cost = {(1,1):4, (1,2):6, (1,3):9,
(2,1):5, (2,2):4, (2,3):7,
(3,1):6, (3,2):3, (3,3):4,
(4,1):8, (4,2):5, (4,3):3,
(5,1):10, (5,2):8, (5,3):4,
}
c = {}
for i in I:
for j in J:
for k in produce[j]:
c[i,j,k] = cost[i,j] * weight[k]
任何建议都会非常受欢迎!
编辑:
根据@abarnert的建议,我添加了I,J,K,重量和成本的值。
{'I': set([(1, 2), (5, 4), (1, 3), (3, 3), (5, 2), (4, 2), (3, 1), (3, 2), (2, 1), (1, 1), (2, 3), (1, 4), (4, 3), (2, 2), (3, 4), (5, 1), (4, 1), (2, 4), (4, 4), (5, 3)])}
{'J': [1, 2, 3]}
{'K': [1, 2, 3]}
{'weight': {1: 5.0, 2: 2.0, 3: 3.0, 4: 4.0}}
{'cost': {(1, 2): 6.0, (3, 2): 3.0, (1, 3): 9.0, (3, 3): 4.0, (5, 2): 8.0, (3, 1): 6.0, (2, 1): 5.0, (2, 3): 7.0, (4, 3): 3.0, (2, 2): 4.0, (5, 1): 10.0, (4, 2): 5.0, (4, 1): 8.0, (1, 1): 4.0, (5, 3): 4.0}}
答案 0 :(得分:0)
您有KeyError作为例外状态:
for i in I:
for j in J:
for k in produce[j]:
c[i,j,k] = cost[i,j] * weight[k]
这里i
是你在第一个循环中创建I
的元组(idcustomer,idproduct),但是成本有元组(idcustomer, idfactory)
作为键,所以在上一个循环中你尝试从成本中获取值使用元组((idcustomer, idproduct), whatever multidict returns)
并且它不正确
答案 1 :(得分:0)
感谢您的建议,我终于找到了解决方案。 我更改了以下代码:
I = set([i for (i,k) in d.iteritems()])
K = set([k for (i,k) in d.iteritems()])
到下面的代码:
I = set([i for [i,j,k] in result])
K = set([j for [i,j,k] in result])
问题是前面的代码产生了我试图创建的两组不正确的结果。