我有以下字典, tempDict
{('M1', 'P1'): 6.0,
('M1', 'P2'): 10.0,
('M1', 'P3'): 4.0,
('M2', 'P1'): 7.0,
('M2', 'P2'): 9.0,
('M2', 'P3'): 5.0}
我正在對這個字典做一些操作,并將一些關鍵組件放到一個串列中。說我有l1 = [], l2 = []。
假設最小值是 4,我發現jobsR as ('M1', 'P3')。我想從 tempDict 中洗掉所有出現“P3”的鍵。
我將迭代地從這個字典中找到最小值并洗掉相應的鍵。由于鍵是有序對,如果離開的鍵元素有第一個組件,M1那么我將在l1else 中的串列中取第二個組件l2。我將繼續,直到字典變空為止。我的代碼是,
while bool(tempDict):
try:
l1 = []
l2 = []
valMin = min(tempDict.values())
jobsR = [key for key in tempDict if tempDict[key] == valMin]
for (x, y) in jobsR:
if x == 'M1':
l1.append(y)
else:
l2.append(y)
remove_list = []
for key, value in tempDict.items():
if jobsR[0][1] in key[1]:
remove_list.append(key)
for item in remove_list:
tempDict.pop(item)
except KeyError:
print('The dictionary has no item now...')
break
預期輸出:
l1 = [P3, P1] and l2 = [P2]
代碼_更新
l1 = []
l2 = []
while bool(tempDict):
valMin = min(tempDict.values())
jobsR = [key for key in tempDict if tempDict[key] == valMin]
remove_list = []
for key, value in tempDict.items():
if jobsR[0][1] in key[1]:
remove_list.append(key)
for item in remove_list:
tempDict.pop(item)
for x in jobsR:
#print(x[0])
if x[0] == 'M1':
l1.append(item[1])
else:
l2.append(item[1])
uj5u.com熱心網友回復:
串列 l1 和 l2 在 while 回圈的每個回圈中都設定為 [ ]。在 while 回圈之外宣告 l1 和 l2 以獲得預期的輸出。
uj5u.com熱心網友回復:
您需要在執行程序中取出l1和l2取出 while 回圈和彈出鍵:
l1 = []
l2 = []
while tempDict:
min_val = min(tempDict.values())
jobsR = [k for k,v in tempDict.items() if v==min_val][0]
if jobsR[0] == 'M1':
l1.append(jobsR[1])
else:
l2.append(jobsR[1])
for k in tempDict:
if k[1]==jobsR[1]]:
tempDict.pop(k)
輸出:
# l1 = ['P3', 'P1']
# l2 = ['P2']
注意:這假設每個最小值都有一個唯一的鍵。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377188.html
上一篇:未處理的例外:型別'_InternalLinkedHashMap<dynamic,dynamic>'不是型別轉換中型別'Map<DateTime,Lis
