代码之家  ›  专栏  ›  技术社区  ›  Sarvagya Dubey

如何在scala的元组数组中使用map函数?

  •  0
  • Sarvagya Dubey  · 技术社区  · 6 年前

    我尝试在Scala shell中执行以下代码:

     var chars = ('a' to 'z').toArray.zipWithIndex
     chars: Array[(Char, Int)] = Array((a,0), (b,1), (c,2), (d,3), (e,4), (f,5), (g,6),
    (h,7), (i,8), (j,9), (k,10), (l,11), (m,12), (n,13), (o,14), (p,15), (q,16), 
    (r,17), (s,18), (t,19), (u,20), (v,21), (w,22), (x,23), (y,24), (z,25))
    

    现在,我希望上面提到的元组数组中每个字符的索引都更新为1,即索引1处的“a”和索引26处的z。如何使用map函数实现这一点?

    4 回复  |  直到 6 年前
        1
  •  1
  •   Lasf    6 年前

    ('a' to 'z').toArray.zipWithIndex.map(t => (t._1, t._2 + 1))
    
        2
  •  1
  •   stack0114106    6 年前

    使用zip而不是zipWithIndex。下面的示例

    scala> var chars = ('a' to 'z').toArray.zip(Stream from 1)
    chars: Array[(Char, Int)] = Array((a,1), (b,2), (c,3), (d,4), (e,5), (f,6), (g,7), (h,8), (i,9), (j,10), (k,11), (l,12), (m,13), (n,14), (o,15), (p,16), (q,17), (r,18), (s,19), (t,20), (u,21), (v,22), (w,23), (x,24), (y,25), (z,26))
    
    scala>
    scala>  var chars = ('a' to 'z').toArray.zip(Stream from 100)
    chars: Array[(Char, Int)] = Array((a,100), (b,101), (c,102), (d,103), (e,104), (f,105), (g,106), (h,107), (i,108), (j,109), (k,110), (l,111), (m,112), (n,113), (o,114), (p,115), (q,116), (r,117), (s,118), (t,119), (u,120), (v,121), (w,122), (x,123), (y,124), (z,125))
    
    scala>
    
        3
  •  1
  •   Leo C    6 年前

    你也可以这样做:

    ('a' to 'z') zip (Stream from 1)
    

    这将产生一个 Vector toArray 也。

        4
  •  1
  •   RAGHHURAAMM    6 年前

    使用,

     var chars = ('a' to 'z').toArray.zipWithIndex
     chars: Array[(Char, Int)] = Array((a,0), (b,1), (c,2), (d,3), (e,4), (f,5), (g,6),
    (h,7), (i,8), (j,9), (k,10), (l,11), (m,12), (n,13), (o,14), (p,15), (q,16), 
    (r,17), (s,18), (t,19), (u,20), (v,21), (w,22), (x,23), (y,24), (z,25))
    
    
        chars.map(x=>{val (a,b)=x;(a,b+1)}) // Here x is each `tuple` in `chars` array.
    // `var (a,b) = x` de-structures(extracts) the tuple into `a and b` where `b`
    // starts from `0`. To make it start from `1`, we use `b+1` for `each tuple` in
    // `map` function
    

    val alpha = 'a' to 'z'
    val s1 = alpha.zip(1 to alpha.size)