本文介绍了用 Scala 替换 List 中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用不可变列表替换索引元素.
How do you replace an element by index with an immutable List.
例如
val list = 1 :: 2 ::3 :: 4 :: List() list.replace(2, 5) 推荐答案除了之前所说的,你还可以使用 patch 函数来替换一个序列的子序列:
In addition to what has been said before, you can use patch function that replaces sub-sequences of a sequence:
scala> val list = List(1, 2, 3, 4) list: List[Int] = List(1, 2, 3, 4) scala> list.patch(2, Seq(5), 1) // replaces one element of the initial sequence res0: List[Int] = List(1, 2, 5, 4) scala> list.patch(2, Seq(5), 2) // replaces two elements of the initial sequence res1: List[Int] = List(1, 2, 5) scala> list.patch(2, Seq(5), 0) // adds a new element res2: List[Int] = List(1, 2, 5, 3, 4)更多推荐
用 Scala 替换 List 中的元素
发布评论