scala案例练习-求各个城市的平均温度

案例练习
求各个城市的平均温度

//需求:求各个城市的平均温度
val d1 = Array(("beijing", 28.1), ("shanghai", 28.7), ("guangzhou", 32.0), ("shenzhen", 33.1))
val d2 = Array(("beijing", 27.3), ("shanghai", 30.1), ("guangzhou", 33.3))
val d3 = Array(("beijing", 28.2), ("shanghai", 29.1), ("guangzhou", 32.0), ("shenzhen", 32.1))

//将城市进行归纳
val data = d1 ++ d2 ++ d3
//进行分组
val groupdata: Map[String, Array[(String, Double)]] = data.groupBy(_._1)
//求和
//第一种方法
val result1 = groupdata.mapValues(arr => {
  val total: (String, Double) = arr.reduce((a, b) => ("", a._2 + b._2))
  val avg = total._2 / arr.length
  avg
})
println("result1:" + result1.toList)
//第二种方法
//tp代表groupdata
val result2: Map[String, Double] = groupdata.map(tp => {
  //求总和:首先找到温度,也就是Array里面的Double
  val total: Double = tp._2.map(_._2).sum
  //求月份的个数
  val month: Int = tp._2.size
  (tp._1, total / month)
})
println("result2:" + result2.toList)
//第三种方法
val result3: Map[String, Double] = groupdata.mapValues(arr => {
  //求总和
  val total: Double = arr.map(_._2).sum
  //月份
  val month: Int = arr.size
  (total / month)
})
println("result3:" + result3.toList)

//第四种方法
val result4 = groupdata.mapValues(arr => {
  val total: Double = arr.foldLeft(0.0)((a, b) => (a + b._2))
  val month: Int = arr.size
  total / month
})
println("result4:" + result4.toList)

//输出
result1:List((shenzhen,32.6), (shanghai,29.3), (guangzhou,32.43333333333333), (beijing,27.86666666666667))
result2:List((shenzhen,32.6), (shanghai,29.3), (guangzhou,32.43333333333333), (beijing,27.86666666666667))
result3:List((shenzhen,32.6), (shanghai,29.3), (guangzhou,32.43333333333333), (beijing,27.86666666666667))
result4:List((shenzhen,32.6), (shanghai,29.3), (guangzhou,32.43333333333333), (beijing,27.86666666666667))

你可能感兴趣的:(陶笔记)