Scala:如何根据Map指定的索引向List插入对应元素?
Scala 列表插入解决方案
问题分析
需要将exampleMap中每个键,按照其对应索引列表插入到exampleList的指定位置,核心难点是避免插入操作导致的索引偏移问题。
通用实现代码
val exampleList = List("A","B","C","D","E","A","L","M","N") val exampleMap = Map("W1" -> Vector(4,8), "W2" -> Vector(5) ) // 1. 将Map转换为(插入索引,键)的操作列表 val insertions = exampleMap.flatMap { case (key, indices) => indices.map(idx => (idx, key)) }.toList // 2. 按索引降序排序,避免插入前面元素导致后续索引偏移 val sortedInsertions = insertions.sortBy(-_._1) // 3. 从后往前执行插入操作 val result = sortedInsertions.foldLeft(exampleList) { case (currentList, (idx, key)) => currentList.patch(idx, List(key), 0) } // 输出结果:List(A, B, C, D, W1, E, W2, A, L, M, W1, N) println(result)
代码解释
- 转换插入操作列表:通过
flatMap将每个键对应的多个索引展开,得到所有需要执行的(索引,键)插入对。 - 降序排序插入操作:从大索引到小索引处理插入,这样前面的插入不会影响后续插入的索引位置(大索引的位置不会因小索引插入元素而偏移)。
- 迭代完成插入:
patch方法第三个参数传0表示在指定索引位置插入元素(而非替换),通过foldLeft迭代执行所有插入操作,逐步构建最终列表。
另一种实现思路(按位置合并)
如果想更直观地按位置组织元素,可以给原元素和插入元素标记优先级,排序后合并:
// 原元素标记为优先级1(后出现),插入元素标记为优先级0(先出现) val originalElements = exampleList.zipWithIndex.map { case (elem, idx) => (idx, 1, elem) } val insertionElements = exampleMap.flatMap { case (key, indices) => indices.map(idx => (idx, 0, key)) }.toList // 按索引和优先级排序,同一索引下插入元素在前 val sortedElements = (originalElements ++ insertionElements).sortBy { case (idx, priority, _) => (idx, priority) } val result = sortedElements.map(_._3)
示例结果说明
你提供的目标结果中未包含W2,推测是示例笔误(exampleMap中W2对应索引5)。上述代码会严格按照exampleMap定义插入所有键,若需忽略W2,只需从exampleMap中移除对应条目即可。
内容的提问来源于stack exchange,提问作者Hima_93
相关产品推荐
相关产品推荐

