代码之家  ›  专栏  ›  技术社区  ›  kingledion

如何从计数列表中获取索引列表?

  •  0
  • kingledion  · 技术社区  · 7 年前

    Array[Int] = Array(0, 1, 0, 2, 1, 0)
    

    我想要一个列表,给我每个条目的索引次数,序列中每个条目的次数。这里的输出是:

    Array[Int] = Array(1, 3, 3, 4)
    

    val func1 = (cnt: Int, idx: Int) => Array.fill(cnt)(idx)
    countarray.zipWithIndex.map(func1)
    
    func1: (Int, Int) => Array[Int] = <function2>
    <console>:132: error: type mismatch;
     found   : (Int, Int) => Array[Int]
     required: ((Int, Int)) => ?
                  seq_of_vectors.map(_.numNonzeros).zipWithIndex.map(func1)
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   jwvh    7 年前

    arr.zipWithIndex.flatMap{case (rep,idx) => Array.fill(rep)(idx)}
    

    使用 flatMap() 所以所有的中间产物 Array s将被夷为一 结果。

    推荐文章