如何将集合分成批次? [英] How can I break a collection into batches?
本文介绍了如何将集合分成批次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里有一个简单的任务:根据批量大小将 n 个元素的 Set 分解为 m 个 Set - 通常我希望将我的子集限制为 1,000 个元素.我写的是这样的,其中input是master,大合集:
I have a simple task here: break a Set of n elements into m Sets based on a batch size - typically I'll want to limit my sub-Sets to 1,000 elements. I wrote something like this, where input is the master, large collection:
var strings = Set[String]() ++ input
var sets = List[Set[String]]()
while (!strings.isEmpty) {
val (head, rest) = strings.splitAt(100)
sets = sets :+ head
securities = rest
}
工作正常,但我认为必须有一个更优雅/更实用的解决方案来解决 Scala 中这样一个简单而常见的问题.有人请赐教.
which works fine, but I am thinking there HAS to be a more elegant/functional solution to such a simple and common problem in Scala. Someone please enlighten me.
推荐答案
并且它存在:.grouped(batchSize)
.示例:
scala> List.range(1,10).toSet.grouped(3).toList
// res0: List[scala.collection.immutable.Set[Int]] = List(
// Set(5, 1, 6),
// Set(9, 2, 7),
// Set(3, 8, 4))
这篇关于如何将集合分成批次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文