【问题标题】:Return tuple through list comprehension [duplicate]通过列表理解返回元组[重复]
【发布时间】:2021-08-27 20:44:35
【问题描述】:

我正在尝试为总分最高的学生返回学生姓名和他们的总分。 我的代码如下。

代码:

# student_grades contains scores (out of 100) for 5 assignments
student_grades = {
    'Andrew': [56, 79, 90, 22, 50],
    'Nisreen': [88, 62, 68, 75, 78],
    'Alan': [95, 88, 92, 85, 85],
    'Chang': [76, 88, 85, 82, 90],
    'Tricia': [99, 92, 95, 89, 99]
}

# calculate the top student and their total points
list_of_student_grades = list(student_grades.items())

top_student = tuple([(name, sum(grades)) for (name, grades) in list_of_student_grades if
                     sum(grades) == max([sum(grades) for name, grades in list_of_student_grades])])

print(list_of_student_grades)
print(top_student)

输出:

[('Andrew', [56, 79, 90, 22, 50]), ('Nisreen', [88, 62, 68, 75, 78]), ('Alan', [95, 88, 92, 85, 85]), ('Chang', [76, 88, 85, 82, 90]), ('Tricia', [99, 92, 95, 89, 99])]
(('Tricia', 474),)

我有两个问题... 首先,为什么输出不只是 ('Tricia', 474) (为什么额外的逗号和括号集)? 其次,有没有更好的方法来解决这个问题?

提前谢谢你!

【问题讨论】:

  • sum_of_points = [(k, sum(student_grades[k])) for k in student_grades.keys()] 这将返回元组列表,其中第一项是学生姓名,下一项是点的总和。
  • 单线解决方案: tuple(map(lambda x: max(x.items(), key=lambda v:v[1]),[dict(zip(student_grades.keys(), map(sum,student_grades.values())))])) 输出为(('Tricia', 474),)

标签: python tuples list-comprehension


【解决方案1】:

您创建了一个仅包含一个元组的列表,当传递给tuple 时会生成一个仅包含一个元组的元组。

您真正想要的只是名称/总和对列表的最大值,最大值被定义为总和最大的对。

>>> max([(name, sum(grades)) for name, grades in list_of_student_grades], key=lambda x: x[1])
('Tricia', 474)

一种可能的替代方法是简单地计算总和最高的学生的姓名,然后重新计算他​​们的总和以构建所需的元组。计算 Tricia 的成绩两次是多余的,我不知道这看起来是否更好,但我认为它很有趣,值得一提。

>>> def compute_sum(name):
...  return sum(student_grades[name])
...
>>> (name:=max(student_grades, key=compute_sum), compute_sum(name))
('Tricia', 474)

【讨论】:

  • 返回最大值确实比返回符合条件的第一项为最大值...
  • 我刚刚输入了这个精确的解决方案,你打败了我——是的,最初的实现是重新实现max 的一种非常迂回的方式。 :)
猜你喜欢
  • 2020-09-30
  • 2021-10-06
  • 1970-01-01
  • 2017-11-28
  • 2023-04-06
  • 2021-11-06
  • 2015-07-22
  • 1970-01-01
相关资源
最近更新 更多