第十章 Scala 容器基础(十一):使用zip或者zipWithIndex来创建一个循环计数器
Problem 你要遍历一个有序集合,同时你又想访问一个循环计数器,但最重要的是你真的不需要手动创建这个计数器。 Solution 使用 zipWithIndex活着 zip方法来自动地创建一个计数器,假设你有一个有序集合days,那么 你可以使用zipWithIndex和counter来打印带有计数器的集合元素: scala> val days = Array("Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday") days: Array[String] = Array(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday) scala> days.zipWithIndex.foreach{case(day,count) => println(s"$count is $day")} 0 is Sunday 1 is Monday 2 is Tuesday 3 is Wednesday 4 is Thursday 5 is Friday 6 is Saturday 同样,你可以使用for循环来打印计数器和集合元素 scala> for((day,count) <- days.zipWithIndex) { |