如何简化这个'for'循环?

时间:2010-12-28 14:32:38

标签: scala

val xsa = List(1,2,3)
val xsb = List(1,2,3)
for (i <- 0 until xsa.size) {
    val a = xsa(i)
    val b = xsb(i)
    println(a + "_" + b)
}

我想简化长度等于'List或Array。我希望这样做:

for (a <- xsa; b <- xsb)
    println(a + "_" + b)

但为什么它只迭代xsb一次?

3 个答案:

答案 0 :(得分:19)

for ((a,b) <- xsa zip xsb)
  println(a + "_" + b)

答案 1 :(得分:8)

(xsa, xsb).zipped foreach ((a, b) => println (a + "_" + b))

或者

(xsa, xsb).zipped map (_ + "_" + _) foreach println

答案 2 :(得分:1)

尝试Seq.zip

val x = xsa.zip(xsb)
for ((a, b) <- x)
    println(a + "_" + b)