如何拆分一个迭代器? [英] How to split up an Iterator?
本文介绍了如何拆分一个迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将迭代器拆分为具有重复项和其余部分的前缀?例如,
How to split an iterator into a prefix with duplicates and the rest ? For instance,
def splitDupes(it: Iterator[Int]): (Iterator[Int], Iterator[Int]) = ???
val (xs, ys) = splitDupes(List(1, 1, 1, 2, 3, 4, 5).iterator)
xs.toList // List(1, 1, 1)
ys.toList // List(2, 3, 4, 5)
val (xs, ys) = splitDupes(List(1, 2, 3, 4, 5).iterator)
xs.toList // List(1)
ys.toList // List(2, 3, 4, 5)
val (xs, ys) = splitDupes(List(1, 1, 1, 1, 1).iterator)
xs.toList // List(1, 1, 1, 1, 1)
ys.toList // List()
val (xs, ys) = splitDupes(List[Int]().iterator)
xs.toList // List()
ys.toList // List()
我可以用它按块读取文本文件吗?
Can I use it to read a text file by chunks ?
推荐答案
您可以使用span
方法将Iterable
拆分为满足谓词的前缀和不满足条件的后缀.对于Iterator
s span
做正确的事情,并且在前缀用完之前迭代后缀的情况下,将元素懒惰地存储在前缀Iterator
中.
You can use the span
method to split an Iterable
into a prefix that satisfies a predicate and a suffix that doesn't. For Iterator
s span
does the correct thing, and lazily stores elements in the prefix Iterator
, in case the suffix was iterated before the prefix has run out.
def splitDupes[T](it: Iterator[T]): (Iterator[T], Iterator[T]) = {
if (it.isEmpty) (Iterator.empty, Iterator.empty)
else {
val head = it.next()
val (dupes, rest) = it.span(_ == head)
(Iterator(head) ++ dupes, rest)
}
}
示例:
scala> val (dupes, rest) = splitDupes(Iterator(1,1,1,2,3,2,1))
dupes: Iterator[Int] = <iterator>
rest: Iterator[Int] = <iterator>
scala> (dupes.toList, rest.toList)
res1: (List[Int], List[Int]) = (List(1, 1, 1),List(2, 3, 2, 1))
这篇关于如何拆分一个迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文