【发布时间】:2013-02-02 04:28:31
【问题描述】:
我有一个循环遍历的数据库,并且根据某些条件,我将相关的数据库条目发送到我创建的字典。然后我想从这个字典中随机选择一个,将它存储在一个列表中,清除字典,然后用递增的变量再次执行整个操作。仅供参考,['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
这里的任何帮助将不胜感激。谢谢。
【问题讨论】:
-
代码无法正常工作,因为一切都取决于您的随机函数返回值。我认为你可能需要修改你的逻辑。
-
不确定我是否理解为什么 for 循环似乎填充了 next_move 字典,并且之后的行将其重新分配给其他内容?
-
抱歉,重新分配后的行是上次尝试修复它时留下的,我在单独的函数中进行了整个数据库搜索。那次尝试没有奏效,所以我恢复了。我已删除有问题的行。
-
Re:代码取决于随机函数... random.choice 可能会触发错误,但它不会导致它。即使我只是拉出字典中的第一项,也无法解决字典没有重新填充更新信息的根本问题。
-
你能提供一些示例输入,数据库数据吗?
标签: python loops dictionary while-loop