用 Scala 替换 List 中的元素 [英] Replace element in List with scala
本文介绍了用 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 中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文