使用迭代器中除最后一个元素之外的所有元素 [英] Use all but the last element from an iterator

查看:44
本文介绍了使用迭代器中除最后一个元素之外的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Vec分成相等长度的某些部分,然后在它们上进行map.我有一个调用Vecchunks()方法产生的迭代器.这可能会使我留下比其他零件小的零件,这将是它产生的最后一个元素.

I want to split a Vec into some parts of equal length, and then map over them. I have an iterator resulting from a call to Vec's chunks() method. This may leave me with a part that will be smaller than other parts, which will be the last element generated by it.

为确保所有部分的长度相等,我只想删除最后一个元素,然后在剩下的位置调用map().

To be sure that all parts have equal length, I just want to drop that last element and then call map() on what's left.

推荐答案

塞巴斯蒂安·雷德尔(Sebastian Redl)指出,然后检查len每个大块的gth是针对您的特定情况的更好解决方案.

As Sebastian Redl points out, checking the length of each chunk is the better solution for your specific case.

要回答您提出的问题(使用除迭代器中的最后一个元素之外的所有元素"),可以使用

To answer the question you asked ("Use all but the last element from an iterator"), you can use Iterator::peekable to look ahead one. That will tell you if you are on the last item or not and you can decide to skip processing it if so.

let things = [0, 1, 2, 3, 4];

let mut chunks = things.chunks(2).peekable();
while let Some(chunk) = chunks.next() {
    if chunks.peek().is_some() {
        print!("Not the last: ");
    } else {
        print!("This is the last: ")
    }

    println!("{:?}", chunk);
}

为确保所有部分的长度相等,我只想删除最后一个元素

To be sure that all parts have equal length, I just want to drop that last element

总是删除最后一个元素不会.例如,如果您平均分块输入,那么始终删除最后一个元素将丢失整块.您必须进行一些预先计算才能确定是否需要删除它.

Always dropping the last element won't do this. For example, if you evenly chunk up your input, then always dropping the last element would lose a full chunk. You'd have to do some pre-calculation to decide if you need to drop it or not.

这篇关于使用迭代器中除最后一个元素之外的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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