【问题标题】:Edit dictionary using only list comprehension仅使用列表理解编辑字典
【发布时间】:2019-03-22 13:56:56
【问题描述】:

数据保存在一个列表中,其元素是字典,其中每个字典包含单个学生的数据:学生的 ID 号、科目的姓名以及他/她在每个科目中获得的分数两个部分考试,分别。每个字典的格式如下:

{'ID' : _IDnumber_, 'subject' : _'Artificial Intelligence'_, 'Partial Exam 1' : _points1_, 'Partial Exam 2' : _points2_}

现在我需要定义一个函数sum_partials(),它接收一个参数——包含学生数据的字典列表(如上所述),并返回相同的列表,但修改为每个字典将只包含部分考试的总分(即总分),而不是两次部分考试的分数。

例如。结果:

[{'ID': 12217, 'subject': 'Artificial Intelligence', 'Total score': 55}, {'ID': 13022, 'subject': 'Artificial Intelligence', 'Total score': 85}, {'ID': 13032, 'subject': 'Artificial Intelligence', 'Total score': 47}]

我已经通过使用一个函数来编辑每个学生,我将这个函数称为列表理解上的表达式:

def sum_partials(results):
    # your code here

  def update_student(student):
    partial_exam1 = student['Partial Exam 1']
    partial_exam2 = student['Partial Exam 2']
    student.pop('Partial Exam 1')
    student.pop('Partial Exam 2')
    student['Total score'] = partial_exam1 + partial_exam2
    return student

  return [update_student(student) for student in results]

它运行完美,但我是 Python 新手,我想知道我是否可以重构我的代码!?是否有一种解决方案可以仅使用列表推导或嵌套列表推导在一行中执行此操作? 我的意思是,要在没有update_student() 函数的情况下完成我需要做的所有事情,而只能通过使用list comprehensions 来完成?

【问题讨论】:

  • 如果您的代码符合预期并且您希望帮助改进/重构它,请查看code review
  • 您的返回值已经是一个列表理解。您的问题归结为,有没有办法将函数 update_student 变成单行代码? 即使有,它也不太可能像您已经拥有的那样具有可读性书面。可以将student['Total score'] = partial_exam1 + partial_exam2结尾的5行简化为student['Total score'] = student.pop('Partial Exam 1') + student.pop('Partial Exam 2')

标签: python list dictionary


【解决方案1】:

请记住,虽然列表推导有效,但您可能希望优先考虑可读代码,而不是“这种类型的结构只是因为”。

在这里,一个简单的for 循环遍历您的学生列表就可以了。

def sum_partials(list_of_students): 
    for student in list_of_students:
        student['Total score'] = student.pop('Partial Exam 1') + student.pop('Partial Exam 2')

    return list_of_students

感谢@BoarGules 使用pop 进行紧凑的单线计算。

【讨论】:

    【解决方案2】:

    你可以使用下面的listcomp:

    lst = [{'ID': 12217, 'subject': 'Artificial Intelligence', 'Partial Exam 1' : 10, 'Partial Exam 2' : 20}]
    
    [{'ID': i['ID'], 'subject': i['subject'], 'Total score': i['Partial Exam 1'] + i['Partial Exam 2']} for i in lst]
    # [{'ID': 12217, 'subject': 'Artificial Intelligence', 'Total score': 30}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-22
      • 2018-10-04
      • 2021-03-05
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多