用Scala统计学生各门成绩
统计学生各门课程的平均成绩、最低成绩、最高成绩以及男同学、女同学分开测试样例grade1.txt:Id gender Math English Physics301610 male 80 64 78301611 female 65 87 58301612 female 44 71 77301613 female 66 71 91301614 female 70 71 100301615 male
统计学生各门课程的平均成绩、最低成绩、最高成绩以及男同学、女同学分开
测试样例grade1.txt:
Id gender Math English Physics
301610 male 80 64 78
301611 female 65 87 58
301612 female 44 71 77
301613 female 66 71 91
301614 female 70 71 100
301615 male 72 77 72
301616 female 73 81 75
301617 female 69 77 75
301618 male 73 61 65
301619 male 74 69 68
301620 male 76 62 76
301621 male 73 69 91
301622 male 55 69 61
301623 male 50 58 75
301624 female 63 83 93
301625 male 72 54 100
301626 male 76 66 73
301627 male 82 87 79
301628 female 62 80 54
301629 male 89 77 72
import scala.io.Source
val inputfile = Source.fromFile("/home/hadoop-wsy/wangshouyin/workspace/20201004/grade1.txt") //测试样例文件的路径
val lines = inputfile.getLines
val Data = lines.map{_.split(" ")} //将每行按空白字符(包括空格/制表符)分开
val originalData = Data.toList //转成List
val header = originalData.head //获得第一行信息
val courseNames=header.drop(2) //去掉前两列,获取第一行中的课程名
val courseNum = courseNames.length //获取courseNames的长度
val allStudents = originalData.tail //获取除第一行信息外, 剩下的信息
val stuNum = allStudents.length //总的学生人数
val (maleLines,femaleLines) = allStudents partition {_(1)=="male"} //按性别划分为两个容器
val maleNum = maleLines.length //男生人数
val femaleNum = femaleLines.length //女生人数
//全部同学
for(i<- 2 to courseNum+1){
val temp = allStudents map {elem => elem(i).toDouble} ; println("for 循环结果:temp,avg,max,min");println(temp.sum/stuNum,temp.min,temp.max)} //对每门课程生成一个三元组,分别表示总分,最低分和最高分
val result1=
(for(i<- 2 to courseNum+1) yield {
val temp = allStudents map {elem=>elem(i).toDouble} ;(temp.sum/stuNum,temp.min,temp.max)}) //for推导式,将for的结果放在result中,result是一个向量,向量中的元素个数等于课程门数,每一个元素是一个三元组tuple,对每门课程生成一个三元组,分别表示平均分,最低分和最高分
//输出结果
for(i<- 0 to courseNum-1)
{println(courseNames(i));println("avg,min,max:");println(result1(i)) }
//男同学
for(i<- 2 to courseNum+1){
val temp = maleLines map {elem => elem(i).toDouble} ; println("for 循环结果:male,avg,max,min");println(temp.sum/maleNum,temp.min,temp.max)}
val result2=
(for(i<- 2 to courseNum+1) yield {
val temp = maleLines map {elem=>elem(i).toDouble} ;(temp.sum/maleNum,temp.min,temp.max)
})
for(i<- 0 to courseNum-1)
{println(courseNames(i));println("avg,min,max:(male)");println(result2(i)) }
//女同学
for(i<- 2 to courseNum+1){
val temp = femaleLines map {elem => elem(i).toDouble} ; println("for 循环结果:female,avg,max,min");println(temp.sum/femaleNum,temp.min,temp.max)}
val result3=
(for(i<- 2 to courseNum+1) yield {
val temp = femaleLines map {elem=>elem(i).toDouble} ;(temp.sum/femaleNum,temp.min,temp.max)})
for(i<- 0 to courseNum-1)
{println(courseNames(i));println("avg,min,max:(female)");println(result3(i)) }
结果截图:
![Logo](https://devpress.csdnimg.cn/79de2bf0b7994defa4242ef90d5513fa.jpg)
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)