我有兩本字典,我想根據以下條件將我的產品字典拆分為串列:
product = {
'k1': 30.99999999999994,
'k2': 400.0,
'k3': 50.0,
'k4': 400.00000000000006,
'k5': 400.0,
'k6': 50.0,
'k7': 60.0,
'k8': 300.0,
'k9': 40.0}
types = {
'k1': 2,
'k2': 1,
'k3': 1,
'k4': 1,
'k5': 1,
'k6': 1,
'k7': 1,
'k8': 1,
'k9': 2}
- 1 - 如果一個產品的價值小于 200 應該加入其他產品,而新的產品串列的價值小于 600
- 2 - 不同型別的產品無法加入
我已經撰寫了以下代碼,但它在字典的最后一個索引上有一個錯誤,我每次都得到錯誤的結果。
k = list(product.keys())
ProductValue = []
ProductName = []
for idx, name in enumerate(k):
value = product[name]
if idx == 0:
temp1 = [value]
temp2 = [name]
continue
if idx == len(k) - 1:
ProductValue.append(temp1)
ProductName.append(temp2)
continue
if value < 200 or product[k[idx - 1]] < 200:
sec1 = types[k[idx - 1]]
sec2 = types[k[idx]]
if ((sum(temp1) value) > 600) or (sec1 != sec2):
ProductValue.append(temp1)
ProductName.append(temp2)
temp1 = [value]
temp2 = [name]
continue
else:
temp1.append(value)
temp2.append(name)
else:
ProductValue.append(temp1)
ProductName.append(temp2)
temp1 = [value]
temp2 = [name]
我從這段代碼中得到的是:
ProductValue = [[30.99999999999994], [400.0, 50.0], [400.00000000000006], [400.0, 50.0, 60.0], [300.0]]
ProductName = [['k1'], ['k2', 'k3'], ['k4'], ['k5', 'k6', 'k7'], ['k8']]
缺少最后一個值為 40 的產品。我嘗試修復我的代碼,但我讓它變得更糟
uj5u.com熱心網友回復:
編輯:
請按照添加的評論修復錯誤并洗掉條件idx==len(k)-1
product = {
'k1': 30.99999999999994,
'k2': 400.0,
'k3': 50.0,
'k4': 400.00000000000006,
'k5': 400.0,
'k6': 50.0,
'k7': 60.0,
'k8': 300.0,
'k9': 40.0}
types = {
'k1': 2,
'k2': 1,
'k3': 1,
'k4': 1,
'k5': 1,
'k6': 1,
'k7': 1,
'k8': 1,
'k9': 2}
k = list(product.keys())
ProductValue = []
ProductName = []
# create empty sublists
temp1 = []
temp2 = []
for idx, name in enumerate(k):
value = product[name]
if idx == 0:
temp1 = [value]
temp2 = [name]
continue
if value < 200 or product[k[idx - 1]] < 200:
sec1 = types[k[idx - 1]]
sec2 = types[k[idx]]
if ((sum(temp1) value) > 600) or (sec1 != sec2):
ProductValue.append(temp1)
ProductName.append(temp2)
temp1 = [value]
temp2 = [name]
continue
else:
temp1.append(value)
temp2.append(name)
else:
# append temp1 and temp1 when for condition fails
ProductValue.append(temp1)
ProductName.append(temp2)
temp1 = [value]
temp2 = [name]
else:
# append the last element to the output list
ProductValue.append(temp1)
ProductName.append(temp2)
print(ProductName)
print(ProductValue)
輸出:
[(['k1'], [30.99999999999994]),
(['k2', 'k3'], [400.0, 50.0]),
(['k4'], [400.00000000000006]),
(['k5', 'k6', 'k7'], [400.0, 50.0, 60.0]),
(['k8'], [300.0]),
(['k9'], [40.0])]
輸入2:
product = {
'k1': 30.99999999999994,
'k2': 400.0,
'k3': 50.0,
'k4': 400.00000000000006,
'k5': 400.0,
'k6': 50.0,
'k7': 60.0,
'k8': 300.0,
'k9': 40.0}
types = {
'k1': 2,
'k2': 1,
'k3': 1,
'k4': 1,
'k5': 1,
'k6': 1,
'k7': 1,
'k8': 1,
'k9': 1}
輸出:
[(['k1'], [30.99999999999994]),
(['k2', 'k3'], [400.0, 50.0]),
(['k4'], [400.00000000000006]),
(['k5', 'k6', 'k7'], [400.0, 50.0, 60.0]),
(['k8', 'k9'], [300.0, 40.0])]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496877.html
