如何加入两个数组是scala
how to join two array is scala
假设我有两个数组
val x =Array("one","two","three")
val y =Array("1","2","3")
获得新数组的最优雅方法是什么
["one1","two2","three3"]
使用 zip
和 map
应该可以做到:
(x zip y) map { case (a, b) => a + b }
与@m-z 类似,带有 for 理解,像这样,
for ( (a,b) <- x zip y ) yield a + b
这可以封装成一个隐含的如
implicit class StrArrayOps(val x: Array[String]) extends AnyVal {
def join(y: Array[String]) =
for ( (a,b) <- x zip y ) yield a + b
}
并像这样使用它,
x join y
Array(one1, two2, three3)
替代zip
:
(0 until math.min(x.length, y.length))
.map(i => x(i) + y(i))
.toArray
假设我有两个数组
val x =Array("one","two","three")
val y =Array("1","2","3")
获得新数组的最优雅方法是什么 ["one1","two2","three3"]
使用 zip
和 map
应该可以做到:
(x zip y) map { case (a, b) => a + b }
与@m-z 类似,带有 for 理解,像这样,
for ( (a,b) <- x zip y ) yield a + b
这可以封装成一个隐含的如
implicit class StrArrayOps(val x: Array[String]) extends AnyVal {
def join(y: Array[String]) =
for ( (a,b) <- x zip y ) yield a + b
}
并像这样使用它,
x join y
Array(one1, two2, three3)
替代zip
:
(0 until math.min(x.length, y.length))
.map(i => x(i) + y(i))
.toArray