0

我有一个循环遍历的数据库,并且根据某些条件,我将相关的数据库条目发送到我创建的字典。然后我想从这本字典中随机选择一个,将它存储在一个列表中,清除字典,然后用递增的变量再次执行整个操作。仅供参考,['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

这里的任何帮助将不胜感激。谢谢。

4

2 回答 2

0

一个可能的问题是:

int(each['DestFing'])总是相同的,那么字典中的相同键将被更新并且计数将保持为 1。

于 2013-02-02T05:21:48.800 回答
0

您正在尝试使用cost_database迭代器两次。在您第一次通过后,它已经耗尽,因此第二次尝试使用它时,整个for循环将被跳过,因为它有一个空的迭代器。

>>> a = xrange(4)
>>> for i in a:
...    print(i)
0
1
2
3
4
>>> for i in a:
...    print(i)
>>> # Nothing since 'a' is already exhausted.
于 2013-02-02T10:13:13.460 回答