2013-04-07 36 views
0

我正在苦苦尋找一個漂亮的noob,這在PHP中相當平凡,但我對Python相當陌生。我有一個方法,查詢數據庫的用戶測試數據,然後用幾個關鍵字構建一個字符串:將傳遞給模板的值。Python中的多級列表

def getTests(self, id): 
    results = [] 
    count = 0 
    tests = TestAttempts.objects.all().filter(user_id=id) 

    for test in tests: 
     title = self.getCourseName(test.test_id) 
     results[count].append([{'title': title, 'finished': test.grade_date_time, 'grade': test.test_grade}]) 
     count += 1 
    return results 

我希望做一個多級列表,我可以遍歷的模板來顯示測試題,完成日期和檔次。

我收到以下錯誤:

list index out of range 
Request Method: GET 
Request URL: http://127.0.0.1:8000/dash/history/ 
Django Version: 1.4.3 
Exception Type: IndexError 
Exception Value:  
list index out of range 

上最好的方法任何幫助,將不勝感激。 謝謝

回答

3

你不需要count變量。

results.append([{'title': title, 'finished': test.grade_date_time, 'grade': test.test_grade}]) 

list.append(x)無論如何,操作會將項目添加到列表的末尾。

+3

此外,你可能要追加隻字典而不是包含字典的列表。這個代碼會產生一個像[[[{'title':'foo',...}],[{'title':'lol',...}]]''的列表,如果你只是做' results.append({...})''它會更容易用'[{'title':'foo',...},{'title':'lol',.. }]'。 – Dougal 2013-04-07 16:35:08

+0

感謝您的這一點,不知道爲什麼在列表中的字典,但完全沒有必要 – xXPhenom22Xx 2013-04-07 16:49:12

0
count

results[count].append([{'title': title, 'finished': test.grade_date_time, 'grade': test.test_grade}]) 

而非索引,你應該直接調用append方法:

results[count].append([{'title': title, 'finished': test.grade_date_time, 'grade': test.test_grade}]) 

此外,要追加包含一個字典的列表。除非你想要做的是extend結果通過將每個字典到列表(未在本例中發生),它可能是不必要的:

results[count].append({'title': title, 'finished': test.grade_date_time, 'grade': test.test_grade})