【问题标题】:Summing up a list in a dictionary在字典中总结一个列表
【发布时间】:2022-10-08 02:31:56
【问题描述】:

我想总结一下 For 循环中的要点。 正如您在我的代码中看到的那样,“点”中的元素(条目)数量是不同的。 有人可以帮我实现这个pytonically吗?

student1 = {'name': 'Hans', 'points': [285, 210, 135, 100, 300]}
student2 = {'name': 'Peter', 'points': [65, 56, 48]}

students = [student1, student2]

for stud in students:
    sumpoints = stud['points'][0]+stud['points'][1]+stud['points'][2]

print(sumpoints)]

【问题讨论】:

  • 提示:使用sum函数
  • 你能澄清一下吗? sumpoints 是单个学生的总分,还是所有学生的总分?

标签: python


【解决方案1】:

如果你想要所有学生的总分,它看起来像这样:

sumpoints = 0
for stud in students:
    sumpoints += sum(stud['points'])

【讨论】:

    【解决方案2】:

    sum 函数将在不指定大小的情况下对列表求和,并且列表理解会将其应用于每个学生。

    student1 = {'name': 'Hans', 'points': [285, 210, 135, 100, 300]}
    student2 = {'name': 'Peter', 'points': [65, 56, 48]}
    
    students = [student1, student2]
    
    sumpoints = [sum(student['points']) for student in students]
    print(sumpoints)
    

    输出是每个学生的总和

    [1030, 169]
    

    【讨论】:

      【解决方案3】:

      感谢您的快速回复。 这不是我想要的,我希望它输出如下:

      汉斯:1030 彼得:169

      这就是为什么我把它放在一个 for 循环中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-19
        • 2023-01-11
        • 2021-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-23
        相关资源
        最近更新 更多