是否可以使用迭代器将向量分成10组? [英] Is it possible to split a vector into groups of 10 with iterators?
问题描述
我有let my_vec = (0..25).collect::<Vec<_>>()
,我想将my_vec
分成10个一组的迭代器:
I have let my_vec = (0..25).collect::<Vec<_>>()
and I would like to split my_vec
into iterators of groups of 10:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19];
[20, 21, 22, 23, 24, None, None, None, None, None];
是否可以在Rust中使用迭代器来做到这一点?
Is it possible to do that with iterators in Rust?
推荐答案
There is no such helper method on the Iterator
trait directly. However, there are two main ways to do it:
-
使用
[T]::chunks()
方法(可以直接在Vec<T>
上调用).但是,它之间的差别很小:它不会产生None
,但是最后一次迭代会产生较小的切片.
Use the
[T]::chunks()
method (which can be called on aVec<T>
directly). However, it has a minor difference: it won't produceNone
, but the last iteration yields a smaller slice.
示例:
let my_vec = (0..25).collect::<Vec<_>>();
for chunk in my_vec.chunks(10) {
println!("{:02?}", chunk);
}
结果:
[00, 01, 02, 03, 04, 05, 06, 07, 08, 09]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24]
使用 Itertools::chunks()
方法(来自板条箱itertools
).此板条箱扩展了标准库中的Iterator
特性,因此该chunks()
方法适用于所有迭代器!请注意,用法要稍微复杂些才能通用.这具有与上述方法相同的行为:在上一次迭代中,块将较小,而不是包含None
s.
Use the Itertools::chunks()
method from the crate itertools
. This crate extends the Iterator
trait from the standard library so this chunks()
method works with all iterators! Note that the usage is slightly more complicated in order to be that general. This has the same behavior as the method described above: in the last iteration, the chunk will be smaller instead of containing None
s.
示例:
extern crate itertools;
use itertools::Itertools;
for chunk in &(0..25).chunks(10) {
println!("{:02?}", chunk.collect::<Vec<_>>());
}
结果:
[00, 01, 02, 03, 04, 05, 06, 07, 08, 09]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24]
这篇关于是否可以使用迭代器将向量分成10组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!