【问题标题】:Looping through a list that contains dicts and displaying it a certain way循环遍历包含 dicts 的列表并以某种方式显示它
【发布时间】:2016-05-10 02:14:21
【问题描述】:

这些是我用 4 个相同的键创建的 3 个字典,但当然是不同的值。

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]

我想做的是遍历列表并像这样显示每个:

"""
student's Name: val
student's Homework: val
student's Quizzes: val
student's Tests: val
"""

我在想一个 for 循环可以解决问题 for student in students: 并且我可以将每个循环存储在一个空的字典中 current = {} 但在那之后我就迷路了。我打算使用 getitem,但我认为这行不通。

提前致谢

【问题讨论】:

  • 那些字典基本上是穷人的课。如果您熟悉 Python 的类和面向对象的编程,您可以使用 transcript 方法创建一个 Student 类(或者直接覆盖 __str__ 魔术方法)。然后,您只需在for student in students: 循环中打印student.transcript() 或str(student)。 (如果下一个处理该数据的函数或程序需要 dict,请将数据保留在 dict 中。)
  • ChrisSlightGhost 按键打印顺序对您来说很重要吗?

标签: python for-loop dictionary


【解决方案1】:

你可以这样做:

students = [lloyd, alice, tyler]

def print_student(student):
    print("""
        Student's name: {name}
        Student's homework: {homework}
        Student's quizzes: {quizzes}
        Student's tests: {tests}
    """.format(**student)) # unpack the dictionary

for std in students:
    print_student(std)

【讨论】:

  • 谢谢,我真的很感激。
【解决方案2】:

使用下面的循环显示所有学生数据无需硬编码键:

# ... 
# Defining of lloyd, alice, tyler
# ...

students = [lloyd, alice, tyler]
for student in students:
    for key, value in student.items():
        print("Student's {}: {}".format(key, value))

祝你好运!

【讨论】:

  • 两点:第一,iteritems在现代Python中已经不存在了,但是items在2和3中都可以使用,所以你不妨使用它。其次,虽然您不对键进行硬编码,但这会丢失所需的输出顺序,因为 dicts 是无序的;对我来说,“name”在输出中排在第三位,感觉很奇怪。
  • @DSM 谢谢你的建议,真的用完了,我已经把iteritems更新成items了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多