用 Scala 替换 List 中的元素

编程入门 行业动态 更新时间:2024-10-27 16:34:46
本文介绍了用 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 中的元素

本文发布于:2023-11-10 15:41:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575775.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   Scala   List

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!