Advertisement
z7z7z7

Untitled

Jun 25th, 2024 (edited)
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.53 KB | None | 0 0
  1. //方法一
  2. val studentScores = allScores.map {
  3.       case (student, score) => (student, (score, 1))
  4.     }
  5. val totalScores = studentScores.reduceByKey {
  6.       case ((score1, count1), (score2, count2)) => (score1 + score2, count1 + count2)
  7.     }
  8. val averageScores = totalScores.map {
  9.       case (student, (totalScore, count)) => (student, totalScore.toDouble / count)
  10.     }
  11.  
  12. //方法二
  13. val averageScores = allScores.mapValues(x => (x,1))
  14. .reduceByKey((x,y) => (x._1+y._1,x._2 + y._2))
  15. .mapValues(x => (x._1 / x._2)).collect()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement