列表选择某些元素

时间:2016-06-06 16:42:32

标签: scala

我正在学习Scala。关于如何从列表中选择某些元素有一个问题。

arr = List(1,2,3,4,5,6,7,8)

例如,我只想得到奇数索引元素=> 2,3,6
或跳过3个元素=> 4,8
我可以出来的唯一方法是循环每个元素并确定,但它应该是一个很好的scala方式来处理这类问题。谢谢。

3 个答案:

答案 0 :(得分:2)

执行此操作的功能是单行,并且不会明确使用索引

val arr = List(1,2,3,4,5,6,7,8)

def getNth[A](xs:List[A], n:Int):List[A] = xs.drop(n-1).grouped(n).map(_.head).toList

getNth(arr, 2)   // List[Int] = List(2, 4, 6, 8)
getNth(arr, 4)   // List[Int] = List(4, 8)

答案 1 :(得分:1)

我能想到的最好方法是使用filterzipWithIndex

scala> List(1,2,3,4,5,6,7,8).zipWithIndex.filter{x => x._2 % 2 == 1}.map{_._1}
res0: List[Int] = List(2, 4, 6, 8)

scala> List(1,2,3,4,5,6,7,8).zipWithIndex.filter{x => x._2 % 3 == 0}.map{_._1}
res1: List[Int] = List(1, 4, 7)

使用toStream会使评估变得懒惰,如果您对效率感兴趣,可能会更有效。

修改

这是另一个,更多(在这种情况下更少)简洁的方法:

scala> List(1,2,3,4,5,6,7,8).zipWithIndex.collect{case(x,i) if i % 2 == 1 => x}
res5: List[Int] = List(2, 4, 6, 8)

答案 2 :(得分:0)

另一个建议:

scala> def withIndices[T](xs:Seq[T])(p: Int => Boolean ) =
          xs.zipWithIndex.filter(x => p(x._2)).unzip._1

scala> val xs = List(1,2,3,4,5,6,7,8)
xs: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)

scala> withIndices(xs)(_%2==1)
res4: Seq[Int] = List(2, 4, 6, 8)

scala> withIndices(xs)(_%3==0)
res5: Seq[Int] = List(1, 4, 7)