如何求和列表中的整数和浮点数的总和-Scala [英] How to sum number of Ints and Number of Floats within a List - Scala

查看:385
本文介绍了如何求和列表中的整数和浮点数的总和-Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算我在Map中的整数和浮点数,就像Map[String, List[(Int, String, Float)]]

I need to calculate the number of integers and floats i have in a Map which is like Map[String, List[(Int, String, Float)]]

数据来自读取文件-例如,内部数据看起来有点像(但是还有更多的路由):

The data comes from reading a file - the data inside for example looks kinda like (however there is a few more 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

地图被拆分,因此字符串是路线的名称,列表是其余的数据.

The map is split so that the String is the name of the route and the List is the rest of the data.

我希望它计算每条路线的检查点"数量以及每条路线的总距离(即浮动距离),然后打印出例如乌尔·伍利路线(Wor Wullie Route)有6个检查站,总距离为18.45公里

I want it to calculate the number of 'checkpoints' per route and total distance of each route (which is the float) then print out e.g. Oor Wullie Route has 6 checkpoints and total distance of 18.45km

我猜我需要使用foldLeft,但是我不确定该怎么做?

I am guessing I need to use a foldLeft however i am unsure how to do so?

我之前做过的简单折叠示例,但不确定如何将其应用于上述情况吗?

Example of a simple fold i have done before but not sure how to apply one to above scenario?

val list1 = List.range(1,20)

def sum(ls:List[Int]):Int = {
  ls.foldLeft(0) { _ + _}
}

推荐答案

您可以轻而易举地完成此操作,但IMO则没有必要.

You could do this with a fold, but IMO it is unnecessary.

通过简单地获取列表的大小即可知道检查点的数量(假设列表中的每个条目都是一个检查点).

You know the number of checkpoints by simply taking the size of the list (assuming each entry in the list is a checkpoint).

要计算总距离,您可以执行以下操作:

To compute the total distance, you could do:

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)

然后获得打印输出,如:

And then get your printout like:

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")
  }

如果您真的想通过foldLeft同时计算numStopsdistance,那么路易斯对您的问题的评论就是解决方法.

If you really wanted to compute both numStops and distance via foldLeft, Luis's comment on your question is the way to do it.

编辑-根据Luis的要求,将他的评论放在此处并进行一些清理:

edit - per Luis's request, putting his comment in here and cleaning it up a bit:

stops.foldLeft(0 -> 0.0f) { 
   // note: "acc" is short for "accumulated"
   case ((accCount, accDistance), (_, _, distance)) => 
     (accCount + 1) -> (accDistance + distance) 
}

这篇关于如何求和列表中的整数和浮点数的总和-Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆