0

我正在尝试通过 codeacademy 学习 python。任务是制作 3 部字典(为每个学生),然后列出 3 部字典。然后,我应该打印出列表中的所有数据。

我试图以与字典本身相同的方式调用值(lloyd [values]),但随后它说未定义值 o_O。我也尝试过“打印名称”,但错误消息是我没有打印出其中一个值。

非常感谢您的帮助。

 lloyd = {
     "name": "Lloyd",
     "homework": [90.0, 97.0, 75.0, 92.0],
     "quizzes": [88.0, 40.0, 94.0],
     "tests": [75.0, 90.0]
 }
 alice = {
     "name": "Alice",
     "homework": [100.0, 92.0, 98.0, 100.0],
     "quizzes": [82.0, 83.0, 91.0],
     "tests": [89.0, 97.0]
 }
 tyler = {
     "name": "Tyler",
     "homework": [0.0, 87.0, 75.0, 22.0],
     "quizzes": [0.0, 75.0, 78.0],
     "tests": [100.0, 100.0]
 }
 students = [lloyd, alice, tyler]
 for names in students:
     print lloyd[values]
4

6 回答 6

6

如果要打印每个学生的所有信息,则必须遍历学生和存储在字典中的值:

students = [lloyd, alice, tyler]
for student in students:
    for value in student:
        print value, "is", student[value]

但是请注意,字典没有排序,因此值的顺序可能不是您想要的方式。在这种情况下,单独打印它们,使用值的名称作为字符串作为键:

for student in students:
    print "Name is", student["name"]
    print "Homework is", student["homework"]
    # same for 'quizzes' and 'tests'

最后,您还可以使用该pprint模块“漂亮地打印”学生词典:

import pprint
for student in students:
    pprint.pprint(student)
于 2013-07-19T21:46:22.637 回答
2

我建议使用 namedtuple 来提高可读性和可扩展性:

from collections import namedtuple

Student = namedtuple('Student', ['name', 'hw', 'quiz', 'test'])

Alice = Student('Alice', herHWLst, herQuizLst, herTestLst)
Ben = Student('Ben', hisHWLst, hisQuizLst, hisTestLst)

students = [Alice, Ben]

for student in students:
    print student.name, student.hw[0], student.quiz[1], student.test[2] 
    #whatever value you want

如果你真的想创建大量的字典,你可以通过上面的代码阅读它:

for student in students:
    name = student['name']
    homeworkLst = student['homework']
    # get more values from dict if you want
    print name, homeworkLst

在 Python 中访问字典非常快,但创建它们可能没有那么快速和有效。在这种情况下,namedtuple 更实用。

于 2013-07-19T22:29:03.740 回答
2

您可以简单地打印字典的值:

for names in students:
   print names #names are the dictionaries

如果您只想打印名称,请使用以下name键:

for student in students:
    print student['name']
于 2013-07-19T21:37:02.207 回答
0

students字典列表也是如此。然后你想要

for student in students:
    print student['name']

此外,当您想调用字典中的键时,您必须将键名放在引号中,作为字符串:alice[homework]不起作用,因为 Python 认为homework是一个变量。你需要alice['homework']

因此,要很好地查看所有信息,您可以这样做

for student in students:
    for field in student.keys():
        print "{}: {}".format(field, student[field])

您可以尝试使格式更好,例如先打印姓名,在每个新学生之间插入新行等。

于 2013-07-19T21:36:09.733 回答
0

这就是我在codeacademy上解决我的问题的方法。希望有人发现这对学生中的学生有帮助:

print student['name']
print student['homework']
print student['quizzes']
print student['tests']
于 2016-04-01T18:02:26.873 回答
0

这是我让他们接受的。

for name in students:
    print name["name"]
    print name["homework"]
    print name["quizzes"]
    print name["tests"]

这也有效,但他们不会接受。

for name in students:
    print name
于 2016-09-04T17:22:38.867 回答