gpt4 book ai didi

scala - 用于嵌套集合的 zipWithIndex(没有可变状态的发布)

转载 作者:行者123 更新时间:2023-12-01 07:56:25 28 4
gpt4 key购买 nike

有一些嵌套的集合:

val xs = List(
List("a","b"),
List("c"),
List("d", "e", "f"))

我想为嵌套列表的元素创建唯一索引:
val result = List(
List(("a", 0), ("b", 1)),
List(("c", 2)),
List(("d", 3), ("e", 4), ("f", 5)))

这是一个糟糕的解决方案(使用可变状态):
val indexes:List[Int] = xs.flatten.zipWithIndex.map(_._2)
var idx = 0
val result = xs.map(_.map{ el =>
val copy = (el, indexes(idx))
idx = idx + 1
copy
})

如何在没有可变状态的情况下释放此任务?

最佳答案

解决方案 1(使用 fold):

scala> xs.foldLeft((List[List[(String, Int)]](), 0)){ 
case ((r, i), x) => (r:+x.zip(Stream.from(i)), i+x.size)
}._1
res1: List[List[(String, Int)]] = List(List((a,0), (b,1)), List((c,2)), List((d,3), (e,4), (f,5)))

解决方案2(使用递归)
scala> def deepZip[A](ls: List[List[A]], i: Int = 0): List[List[(A, Int)]] = ls match {
| case Nil => Nil
| case x::xs => x.zip(Stream.from(i)) :: deepZip(xs, i+x.size)
| }
deepZip: [A](ls: List[List[A]], i: Int)List[List[(A, Int)]]

scala> deepZip(xs)
res2: List[List[(String, Int)]] = List(List((a,0), (b,1)), List((c,2)), List((d,3), (e,4), (f,5)))

解决方案3:
scala> (xs, xs.map(_.size).scanLeft(0){ _+_ }).zipped map { (a, b) => a.zip(Stream.from(b)) }
res3: List[List[(String, Int)]] = List(List((a,0), (b,1)), List((c,2)), List((d,3), (e,4), (f,5)))

关于scala - 用于嵌套集合的 zipWithIndex(没有可变状态的发布),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25847457/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com