有没有一个快速的scala习惯用法,可以使用索引来检索可遍历的多个元素。
我在找像这样的东西
val L=1 to 4 toList
L(List(1,2)) //doesn't work到目前为止,我一直在使用map,但我想知道是否有更"scala“的方式
List(1,2) map {L(_)}提前感谢
发布于 2013-07-25 01:26:39
List(1,2) map L发布于 2013-07-25 02:05:39
implicit class RichIndexedSeq[T](seq: IndexedSeq[T]) {
def apply(i0: Int, i1: Int, is: Int*): Seq[T] = (i0+:i1+:is) map seq
}然后,您可以对一个或多个索引使用序列的apply方法:
scala> val data = Vector(1,2,3,4,5)
data: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4, 5)
scala> data(0)
res0: Int = 1
scala> data(0,2,4)
res1: Seq[Int] = ArrayBuffer(1, 3, 5)发布于 2013-07-25 01:20:48
您可以使用for理解它,但它并不比使用map的代码更清晰。
scala> val indices = List(1,2)
indices: List[Int] = List(1, 2)
scala> for (index <- indices) yield L(index)
res0: List[Int] = List(2, 3)我认为最具可读性的方法是实现您自己的函数takeIndices(indices: List[Int]),该函数接受一系列索引并返回这些索引中给定List的值。例如:
L.takeIndices(List(1,2))
List[Int] = List(2,3)https://stackoverflow.com/questions/17840425
复制相似问题