val m = Array(10,20,30,30,50,60,70,80) groupBy ( s => s %30 == 0)
m(true).map { kv => println(kv) }
Run Code Online (Sandbox Code Playgroud)
打印值30,30,60
我希望打印索引,即2,3,5.
我该怎么做?
val m = Array(10,20,30,30,50,60,70,80).zipWithIndex.groupBy(s =>
s._1 % 30 == 0).map(e => e._1 -> (e._2.unzip._2))
Run Code Online (Sandbox Code Playgroud)
仅供参考,如果你只想要这些true价值观,那么你可以选择@missoutfaktor的方法,同样你可以partition这样做:
val m = Array(10, 20, 30, 30, 50, 60, 70, 80).zipWithIndex.partition(s =>
s._1 % 30 == 0)._1.unzip._2
Run Code Online (Sandbox Code Playgroud)
Array(10, 20, 30, 30, 50, 60, 70, 80)
.zipWithIndex
.collect { case (element, index) if element % 30 == 0 => index }
// Array[Int] = Array(2, 3, 5)
Run Code Online (Sandbox Code Playgroud)
这是另一种方法:
Array(10,20,30,30,50,60,70,80).zipWithIndex.filter{ _._1 % 30 == 0 }.map{ _._2 }
Run Code Online (Sandbox Code Playgroud)
我觉得.map{ _._2 }比较容易理解.unzip._2,但也许这只是我.有趣的是上面的回报:
Array[Int] = Array(2, 3, 5)
Run Code Online (Sandbox Code Playgroud)
虽然解压缩变量返回:
scala.collection.mutable.IndexedSeq[Int] = ArrayBuffer(2, 3, 5)
Run Code Online (Sandbox Code Playgroud)