在Scala中拆分Range的好方法

时间:2017-03-06 05:43:10

标签: scala

假设我有以下代码,有没有办法简化这个以更美化的方式?

var i = 0
val step = 100
val limitArr = new ArrayBuffer[(Int, Int)]
while (i < rddPartNumber) {
   limitArr += ((i, i + step))
   i += step
}

5 个答案:

答案 0 :(得分:5)

你在做什么基本上是循环一系列数字。这可以通过Range

上的映射来表达
val limits = (0 until rddPartNumber by step) map {i => (i , i + step)}

或者您更喜欢for语法

for {i <- 0 until rddPartNumber by step}
yield (i, i + step)

答案 1 :(得分:2)

scala> val range = 0 to rddPartNumber  by step
scala> range.zip(range.tail)

step等于100且rddPartNumber等于1000

res6: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((0,100), (100,200), (200,300), (300,400), (400,500), (500,600), (600,700), (700,800), (800,900), (900,1000))

如果您确实需要Array,请在将它们压缩后添加toArray

答案 2 :(得分:2)

Array.tabulate用于从arddPartNumber的时间间隔,如下所示

Array.tabulate((rddPartNumber-a)/step) { i => (i*step, i*step+step) }

答案 3 :(得分:1)

这样的东西?

scala> val range = 0 to 444 by 100
range: scala.collection.immutable.Range = inexact Range 0 to 444 by 100

scala> (range zip range.tail).toArray
res0: Array[(Int, Int)] = Array((0,100), (100,200), (200,300), (300,400))

444只是rddPartNumber的占位符。

答案 4 :(得分:1)

您可以使用范围函数构建具有所需步长的列表,然后映射列表以构建元组:

val list = List.range(0, rddPartNumber, step) // List(0, 100, 200, 300, 400, 500, ...)

val tuples = list.map(x => (x, x + step)) // List((0,100), (100,200), (200,300), (300,400), (400,500), (500,600)

val array = tuples.toArray