我有一個數據庫,我循環,並根據特定的條件,我發送相關的數據庫條目到我創建的字典。然後,我想從這本詞典中隨機挑選一個,將它存儲在一個列表中,清除字典,然後用遞增的變量再次完成整個事情。僅供參考,['StartNoteNum']等只是成本數據庫中的列名。爲什麼Python字典不能在while循環中重新填充?
儘管如此,它在第一次徹底循環時工作正常,但如果我嘗試清除代碼中任何地方(while循環內部或外部)的字典,則字典永遠不會重新填充儘管它應該增加值。爲了確認它應該正確地重新填充,我已經將初始值設置爲在while循環中會遇到的所有可能的值,並且每個都在循環中第一次工作,但是一旦嘗試循環就失敗。我得到的錯誤是隨機函數不能從空字典中提取。 Grr ...這裏是代碼。
def compute_policy(clean_midi, cost_database):
note = 0 #Setting up starting variables.
total_score = []
current_finger = 1
path = [1]
next_move = {}
while note <= 2:
current_note = clean_midi[note] #get note-pair for scoring
dest_note = clean_midi[note+1]
for each in cost_database: #find all relevant DB entries
if (int(each['StartNoteNum']) == current_note
and int(each['DestNoteNum']) == dest_note
and int(each['StartFing']) == current_finger):
next_move[int(each['DestFing'])] = int(each['Score']) #move relevant entries to separate "bin"
policy_choice = random.choice(next_move.keys()) #choose one at random
total_score.append(next_move[policy_choice]) #track the scores for each choice in a list
path.append(policy_choice) #track the chosen finger
current_finger = policy_choice #update finger variable
note += 1
path.append(current_finger) #append last finger since the loop won't run again
return total_score, path
這裏的任何幫助將不勝感激。謝謝。
該代碼不會工作,因爲一切都取決於您的隨機函數返回一個值。我認爲你可能需要重新修改你的邏輯。 – asheeshr
不知道我明白爲什麼for循環似乎填充next_move字典,然後將其重新分配給其他內容? – Laurent
對不起,之後的行重新分配它是從以前的嘗試修復它在我做了一個單獨的功能的整個數據庫搜索。這種嘗試沒有奏效,所以我回復了。我已刪除有問題的線路。 – bwest87