我有一个循环遍历的数据库,并且根据某些条件,我将相关的数据库条目发送到我创建的字典。然后我想从这本字典中随机选择一个,将它存储在一个列表中,清除字典,然后用递增的变量再次执行整个操作。仅供参考,['StartNoteNum'] 等只是成本数据库中的列名。
但是会发生什么,它在第一次通过循环时工作正常,但是如果我尝试在代码中的任何位置(在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
这里的任何帮助将不胜感激。谢谢。