← 返回题库
初级

统计各课程平均成绩

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
def solve():
    from pyodide.http import open_url
    instructors_csv = open_url("https://data.zuihe.com/dbd/education/state_D01/instructors.csv").read()
    courses_csv = open_url("https://data.zuihe.com/dbd/education/state_D01/courses.csv").read()
    students_csv = open_url("https://data.zuihe.com/dbd/education/state_D01/students.csv").read()
    enrollments_csv = open_url("https://data.zuihe.com/dbd/education/state_D01/enrollments.csv").read()
    assignments_csv = open_url("https://data.zuihe.com/dbd/education/state_D01/assignments.csv").read()
    submissions_csv = open_url("https://data.zuihe.com/dbd/education/state_D01/submissions.csv").read()
    import sqlite3
    import pandas as pd
    from io import StringIO

    conn = sqlite3.connect(':memory:')
    pd.read_csv(StringIO(submissions_csv)).to_sql('submissions', conn, index=False, if_exists='replace')
    pd.read_csv(StringIO(assignments_csv)).to_sql('assignments', conn, index=False, if_exists='replace')
    pd.read_csv(StringIO(courses_csv)).to_sql('courses', conn, index=False, if_exists='replace')

    result = pd.read_sql_query("""
        SELECT c.title, COUNT(s.id) AS submission_count,
               ROUND(AVG(s.score), 1) AS avg_score
        FROM submissions s
        JOIN assignments a ON s.assignment_id = a.id
        JOIN courses c ON a.course_id = c.id
        GROUP BY c.id, c.title
        ORDER BY avg_score DESC
    """, conn)
    print(result.to_string(index=False))
    conn.close()

示例

输入
solve()
期望输出
title  submission_count  avg_score
 Python自动化办公                 2       93.5
Python数据分析实战                 7       86.1
    SQL数据库实战                 4       85.8
 Python从零到精通                 7       79.9
     算法与数据结构                 3       79.3
  Python爬虫实战                 1       78.0
      机器学习入门                 1       77.0
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码