我执行了这个代码段:
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 i in students:
for f in i:
print i[f]
我不明白为什么输出是下一个:
[88.0, 40.0, 94.0]
[75.0, 90.0]
Lloyd
[90.0, 97.0, 75.0, 92.0]
[82.0, 83.0, 91.0]
[89.0, 97.0]
Alice
[100.0, 92.0, 98.0, 100.0]
[0.0, 75.0, 78.0]
[100.0, 100.0]
Tyler
[0.0, 87.0, 75.0, 22.0]
为什么会这样?哪里可以找到文件?有人能给我简短的输出逻辑解释吗?
答案 0 :(得分:6)
字典键没有定义的顺序。 {'a':1,'b':2}
和{'b':2,'a':1}
被认为是平等的,它们以相同的方式打印出来:
>>> {'a':1, 'b':2}
{'a': 1, 'b': 2}
>>> {'b':2, 'a':1}
{'a': 1, 'b': 2}
另请注意,根据您自己的经验,您不能假设它们会按字母顺序排列。
答案 1 :(得分:6)
答案 2 :(得分:1)
您可以通过更改循环轻松解决此问题:
for student in students:
for key in ["name", "homework", "quizzes", "tests"]:
print student[key]
Namedtuples可能是更好的匹配:
from collections import namedtuple
Student = namedtuple('Student', ["name", "homework", "quizzes", "tests"])
students = [
Student(name="Lloyd",
homework=[90.0, 97.0, 75.0, 92.0],
quizzes=[ 88.0, 40.0, 94.0],
tests=[75.0, 90.0])
Student(name="Alice",
homework=[100.0, 92.0, 98.0, 100.0],
quizzes=[82.0, 83.0, 91.0],
tests=[89.0, 97.0])
Student(name="Tyler",
homework=[0.0, 87.0, 75.0, 22.0],
quizzes=[0.0, 75.0, 78.0],
tests=[100.0, 100.0])
]