Rust迭代器类似于chunks()

这个迭代器

let data = vec![0, 1, 2, 3, 4, 5];

for x in data.chunks(2) {
    println!("{:?}", x);
}

会产生

[0, 1]
[2, 3]
[4, 5]

我可以使用迭代器来获得这样的东西吗?

[0, 1]
[1, 2]
[2, 3]
[3, 4]
[4, 5]
[0, 1]
[1, 2]
[2, 3]
[3, 4]
[4, 5]

我知道如何使用 for 循环来做到这一点。但是迭代器可以做得更好吗?

回答

我想您可以为此使用 Itertools.tuple_windows。根据文档,它“在所有连续窗口上返回一个迭代器,生成特定大小的元组(最多 4 个)”

use itertools::Itertools;
use itertools::TupleWindows;
use std::slice::Iter;

let data = vec![0, 1, 2, 3, 4, 5];

let it: TupleWindows<Iter<'_, i32>, (&i32, &i32)> = data.iter().tuple_windows();

for elem in it {
    println!("{:?}", elem);
}

输出:

(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)

编辑:如@Masklinn的评论1 和@SebastianRedl的评论2 所述,您也可以windows从 stdlib使用并避免包含Itertools在您的项目中。但请注意,它仅适用于切片(或强制切片的事物),而不适用于通用迭代器(在您的情况下很好)。

输出:

  • FWIW there's [`windows`](https://doc.rust-lang.org/std/primitive.slice.html#method.windows) in the stdlib which iterates on slices and would probably be sufficient here.
  • @mgc You should note in your answer that `windows` works only for slices (or things that coerce to them), not general iterators.

以上是Rust迭代器类似于chunks()的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>