繁体   English   中英

Python中的多级列表

[英]Multi-level List in Python

我正在努力解决一个相当愚蠢的事情,这在PHP中是微不足道的,但是我对Python还是很陌生。 我有一个查询数据库以获取用户测试数据的方法,然后用一些key:values构建一个字符串,该字符串将被传递给模板。

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

最好的方法的任何帮助将不胜感激。 谢谢

您不需要count变量。

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

无论如何,list.append(x)操作都会将一个项目添加到列表的末尾。

而不是用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})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM