使用循环来简化Python Dictonaries

dee*_*oeh -1 python dictionary loops

我正在自学Python,我一直在使用Codecademy作为工具.我已经理解了在字典中写某些键的基本前提,但我意识到使用循环向字典添加键会更容易,特别是如果以后必须修改代码,并且每个字典具有相同的值.但是,我无法让我的代码返回我想要的值:

students = {"lloyd" : [], "alice" : [], "tyler" : []}

for student in students:
    student = {
        "name" : [], 
        "homework" : [], 
        "quizzes" : [], 
        "tests" : []
    }

print students
Run Code Online (Sandbox Code Playgroud)

但这回归:

{'tyler': [], 'lloyd': [], 'alice': []}
None
Run Code Online (Sandbox Code Playgroud)

我如何设置它,以便...它......实际上有效,我在学生的名字下有"名字","作业","测试"和"测验"?

a p*_*a p 7

首先,你没有return任何东西.其次,你覆盖了'student'变量,从不保存你创建的值.您应该随时跟踪或修改字典:

students = {"lloyd" : [], "alice" : [], "tyler" : []}

for student in students:
    students[student] = {  # Notice the change here
        "name" : [], 
        "homework" : [], 
        "quizzes" : [], 
        "tests" : []
    }

print students
Run Code Online (Sandbox Code Playgroud)

Python也支持这类的类,尽管你可能还没有完成这部分教程:

class Student: 
    def __init__(self): 
        self.tests = []
        self.quizzes = []
        self.name = ""
        self.homework = []
Run Code Online (Sandbox Code Playgroud)

然后你可以有一些与学生相关的行为:

    def hw_average(self): 
        return sum(self.homework)/len(self.homework) # divide by zero if no homework, so don't actually do this. 
Run Code Online (Sandbox Code Playgroud)

然后你可以与学生互动:

jeff = Student()
jeff.name = "Jeff"
jeff.homework = [85, 92, 61, 78]
jeff.hw_average()  # 79
Run Code Online (Sandbox Code Playgroud)