是否可以使用迭代器将向量分成 10 个组? [英] Is it possible to split a vector into groups of 10 with iterators?

查看:20
本文介绍了是否可以使用迭代器将向量分成 10 个组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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?

推荐答案

Iterator trait 直接.但是,有两种主要方法可以做到这一点:

There is no such helper method on the Iterator trait directly. However, there are two main ways to do it:

  1. 使用 [T]::chunks() 方法(可以直接在 Vec 上调用).但是,它有一个细微的区别:它不会产生 None,但最后一次迭代会产生更小的切片.

  1. Use the [T]::chunks() method (which can be called on a Vec<T> directly). However, it has a minor difference: it won't produce None, 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.这个 crate 扩展了标准库中的 Iterator 特征,所以这个 chunks() 方法适用于所有迭代器!请注意,为了通用,用法稍微复杂一些.这与上述方法具有相同的行为:在最后一次迭代中,块将更小而不是包含 Nones.

  • 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 Nones.

    示例:

    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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆