【问题标题】:How to use map function inside an array of tuples in scala?如何在scala的元组数组中使用map函数?
【发布时间】:2019-03-11 03:13:23
【问题描述】:

我尝试在 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 函数实现这一点?

【问题讨论】:

  • 您想解决这个特定问题(将字母映射到基于 1 的索引),还是这只是您需要解决的问题的一个示例?你有两个方向的答案。

标签: arrays scala collections tuples


【解决方案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)

【讨论】:

  • 非常感谢您的两个答案都一样,第二个更容易理解。请您详细说明第一个。我正在学习,所以没有完全得到第一个答案。再次感谢
  • 请查看解释,现在可能清楚明白了。
【解决方案2】:

你也可以这样做:

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

这将产生一个Vector。如果你想要一个数组,也只需申请toArray

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      这样

      ('a' to 'z').toArray.zipWithIndex.map(t => (t._1, t._2 + 1))
      

      【讨论】:

      • ... 或解构元组,以避免使用那些难看的 _1_2 方法:.map { case (c, i) => (c, i + 1) }
      • @jubobs 完全同意。我讨厌那些方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 2022-10-24
      • 2011-11-29
      • 2020-10-27
      • 2020-01-19
      相关资源
      最近更新 更多