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

时间:2018-10-05 15:06:49

标签: arrays scala collections tuples

我尝试在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 个答案:

答案 0 :(得分:1)

using (PowerShell PowerShellInstance = PowerShell.Create())
 {
    PowerShellInstance.AddScript(powerShellScript);                    
    Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
 } 

答案 1 :(得分:1)

使用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>

答案 2 :(得分:1)

您也可以这样做:

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

这将产生一个Vector。如果需要数组,也只需应用toArray

答案 3 :(得分:1)

使用

 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)