我正在自学Python,我一直在使用Codecademy作为工具。我已经理解了在字典中写入某些键的基本前提,但我意识到使用循环向字典添加键会更容易,尤其是如果以后必须修改代码,并且每个字典具有相同的值。但是,我无法让我的代码返回我想要的值:
students = {"lloyd" : [], "alice" : [], "tyler" : []}
for student in students:
student = {
"name" : [],
"homework" : [],
"quizzes" : [],
"tests" : []
}
print students
但是这会回来:
{'tyler': [], 'lloyd': [], 'alice': []}
None
我如何设置它,以便......它......实际上有效,我有"名称","作业","测试&#34 ;和"测验"一切都在学生的指导下名字?
答案 0 :(得分:6)
首先,你不是return
任何东西。其次,你覆盖了'student'变量,从不保存你创建的值。您应该随时跟踪或修改字典:
students = {"lloyd" : [], "alice" : [], "tyler" : []}
for student in students:
students[student] = { # Notice the change here
"name" : [],
"homework" : [],
"quizzes" : [],
"tests" : []
}
print students
Python也支持类这类的类,尽管你可能还没有完成这部分教程:
class Student:
def __init__(self):
self.tests = []
self.quizzes = []
self.name = ""
self.homework = []
然后您可以将某些行为与学生相关联:
def hw_average(self):
return sum(self.homework)/len(self.homework) # divide by zero if no homework, so don't actually do this.
然后你可以与学生互动:
jeff = Student()
jeff.name = "Jeff"
jeff.homework = [85, 92, 61, 78]
jeff.hw_average() # 79
答案 1 :(得分:1)
问题是您在循环中重新分配student
变量,但原始字典保持不变。
如果你想使用dicts,那么规范的方法是使用工厂函数从模板生成dict,然后用它来创建学生词典。
def make_student(name)
return {
"name" : name,
"homework" : [],
"quizzes" : [],
"tests" : []
}
students = {name : make_student(name) for name in ['lloyd', 'alice' 'tyler']}
print(students)
据说,最好还是上课(另一个答案)。