我需要计算我在Map中的整数和浮点数,就像 Map[String, List[(Int, String, Float)]]
数据来自读取文件-例如,里面的数据看起来有点像(但是还有一些Routes):
Cycle Route (City),1:City Centre :0.75f,2:Main Park :3.8f,3:Central Station:2.7f,4:Modern Art Museum,5:Garden Centre:2.4f,6:Music Centre:3.4f
拆分地图,使“字符串”为路线名称,“列表”为其余数据。
我希望它计算每条路线的“检查点”数量和每条路线的总距离(即浮动车位),然后打印出来,例如Oor Wullie Route有6个检查点,总距离为18.45公里
我猜我需要使用a,foldLeft
但是我不确定该怎么做?
我之前做过的简单折叠示例,但不确定如何将其应用于上述情况吗?
val list1 = List.range(1,20)
def sum(ls:List[Int]):Int = {
ls.foldLeft(0) { _ + _}
}
您可以轻而易举地做到这一点,但是IMO是不必要的。
您只需通过获取列表的大小即可知道检查点的数量(假设列表中的每个条目都是一个检查点)。
要计算总距离,您可以执行以下操作:
def getDistance(list: List[(Int, String, Float)]): Float =
list
.iterator // mapping the iterator to avoid building an intermediate List instance
.map(_._3) // get the distance Float from the tuple
.sum // built-in method for collections of Numeric elements (e.g. Float)
然后像这样获得打印输出:
def summarize(routes: Map[String, List[(Int, String, Float)]]): Unit =
for { (name, stops) <- routes } {
val numStops = stops.size
val distance = getDistance(stops)
println(s"$name has $numStops stops and total distance of $distance km")
}
如果您真的想同时通过numStops
和计算,那么Luis对您的问题的评论就是这样做的方法。distance
foldLeft
编辑-根据Luis的要求,将他的评论放在这里并进行一些清理:
stops.foldLeft(0 -> 0.0f) {
// note: "acc" is short for "accumulated"
case ((accCount, accDistance), (_, _, distance)) =>
(accCount + 1) -> (accDistance + distance)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句