在scala列表中添加元素 [英] add elements in scala lists

查看:872
本文介绍了在scala列表中添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在学习Scala,并且面临以下问题.目前,我在输入

I am still learning Scala and I am facing the following issue. Currently I have the following list in input

val listA=List("banana,africa,1,0",
"apple,europe,1,2",
"peas,africa,1,4")

所需的输出是:

val listB=list("banana,africa,1,0,1",
"apple,europe,1,2,3",
"peas,africa,1,4,5")

我的目的是为列表中的每一行添加一个与最后两个元素之和相对应的元素.我写了以下基本功能

My aim is to add an element corresponding to the sum of the two last elements for each line in the list. I wrote the following basic function

 def addSum(listin:List[String]):List[String]= {
  listin.map(_.split(",")).map(d => d + "," + d(2)+d(3))

}

这没有任何建议,因为请使用更好的方法进行操作

this is not working any suggestion aboit a better way to do it please

非常感谢

推荐答案

简单的解决方案是执行以下操作

Simple solution is to do something like below

listA.map(str => str.split(",")).map(arr => (arr ++ Array(arr(2).toInt+arr(3).toInt)).mkString(","))

这篇关于在scala列表中添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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