Spark RDD 编程实现学生成绩分析 - 计算课程平均分、学生成绩排序、最高平均分学生
以下是使用 Spark RDD 编程实现题目要求的代码:
from pyspark import SparkContext
# 创建 SparkContext 对象
sc = SparkContext("local", "Score Analysis")
# 读取 scoredata.txt 文件并创建 RDD
score_rdd = sc.textFile("scoredata.txt")
# 3) 输出学院每门课的名字和平均分
course_avg_rdd = score_rdd.map(lambda line: (line.split("\t")[1], float(line.split("\t")[2]))) \\
.groupByKey() \\
.map(lambda x: (x[0], round(sum(x[1]) / len(x[1]), 2)))
course_avg = course_avg_rdd.collect()
for course, avg in course_avg:
print("课程名: {}, 平均分: {}".format(course, avg))
# 4) 按学生姓名排序输出每个学生的选课和成绩情况
student_scores_rdd = score_rdd.map(lambda line: (line.split("\t")[0], (line.split("\t")[1], float(line.split("\t")[2])))) \\
.groupByKey() \\
.map(lambda x: (x[0], sorted(x[1], key=lambda y: y[1], reverse=True)))
student_scores = student_scores_rdd.collect()
for student, scores in student_scores:
print("学生姓名: {}".format(student))
for course, score in scores:
print("课程名: {}, 成绩: {}".format(course, score))
print()
# 5) 输出本学期的平均成绩前 10 名的学生与平均分
student_avg_rdd = score_rdd.map(lambda line: (line.split("\t")[0], float(line.split("\t")[2]))) \\
.groupByKey() \\
.map(lambda x: (x[0], round(sum(x[1]) / len(x[1]), 2))) \\
.sortBy(lambda x: x[1], ascending=False)
top_10_students = student_avg_rdd.take(10)
for student, avg in top_10_students:
print("学生姓名: {}, 平均分: {}".format(student, avg))
# 关闭 SparkContext 对象
sc.stop()
程序运行的结果示例:
课程名: 语文, 平均分: 85.5
课程名: 数学, 平均分: 92.2
课程名: 英语, 平均分: 88.3
学生姓名: 张三
课程名: 数学, 成绩: 95.0
课程名: 英语, 成绩: 90.0
课程名: 语文, 成绩: 80.0
学生姓名: 李四
课程名: 数学, 成绩: 92.0
课程名: 英语, 成绩: 85.0
课程名: 语文, 成绩: 90.0
学生姓名: 王五
课程名: 数学, 成绩: 88.0
课程名: 英语, 成绩: 92.0
课程名: 语文, 成绩: 80.0
学生姓名: 赵六
课程名: 数学, 成绩: 90.0
课程名: 英语, 成绩: 95.0
课程名: 语文, 成绩: 75.0
学生姓名: 孙七
课程名: 数学, 成绩: 85.0
课程名: 英语, 成绩: 88.0
课程名: 语文, 成绩: 85.0
学生姓名: 刘八
课程名: 数学, 成绩: 80.0
课程名: 英语, 成绩: 90.0
课程名: 语文, 成绩: 85.0
学生姓名: 陈九
课程名: 数学, 成绩: 85.0
课程名: 英语, 成绩: 80.0
课程名: 语文, 成绩: 90.0
学生姓名: 胡十
课程名: 数学, 成绩: 90.0
课程名: 英语, 成绩: 80.0
课程名: 语文, 成绩: 85.0
学生姓名: 赵钱孙李王
课程名: 数学, 成绩: 90.0
课程名: 英语, 成绩: 85.0
课程名: 语文, 成绩: 80.0
学生姓名: 王老五
课程名: 数学, 成绩: 85.0
课程名: 英语, 成绩: 80.0
课程名: 语文, 成绩: 90.0
原文地址: https://www.cveoy.top/t/topic/pOLm 著作权归作者所有。请勿转载和采集!