在Scala中遍历列表时,如何修改列表的每个元素? [英] How can I modify each element of a list while iterating over it in Scala?

查看:251
本文介绍了在Scala中遍历列表时,如何修改列表的每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样声明的字符串列表:

I have a List of String declared like this:

var re1_emoticons=""::Nil

然后我填入了图释(字符串).我正在尝试在re1_emoticons中每个字符串的开头添加一个\\,以修改原始变量.

Which I have then filled in with emoticons (Strings). I am trying to add a \\ at the beginning of each String in re1_emoticons, modifying the original var.

re1_emoticons.foreach(t=>"""\\""" + t)

第二次尝试:

re1_emoticons.foreach(t=>re1_emoticons.indexOf(t)="""\\"""+ t)

第三次尝试:

re1_emoticons.foreach(t=>re1_emoticons.indexOf(t):="""\\"""+ t)    

但是仍然找不到路.有正确的方法吗?

However still don't find the way. Is there a correct way to do this?

推荐答案

使用map功能.它将创建一个新列表,并将功能应用于每个项目.当您获得新列表时,可以将其分配给您已经拥有的var.

Use the map-function. It creates a new list with a function applied to each of the items. When you get the new list, you can assign it to the var you already have.

re1_emoticons = re1_emoticons.map(t => """\\""" + t)

这篇关于在Scala中遍历列表时,如何修改列表的每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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