获取分区函数中的项目索引

问题描述 投票:1回答:2

我需要在生锈中拆分数组/向量,并在文档中找到partition。看起来传递给partition的回调函数只能访问数组的项目。我如何获得该项目的索引?

例如,给出一个数组[1, 2, 3, 4],我如何根据它们的位置将它分成两个,所以第一个将是[1, 3],因为它们每个都有一个偶数位置(1和3有索引0和2是偶数)和第二个是[2, 4]

rust
2个回答
4
投票

一个解决方案可能是使用来自itertools的enumeratepartition_map

use itertools::{Either, Itertools};

fn main() {
    let a = vec![1, 2, 3, 4];

    let (b, c): (Vec<_>, Vec<_>) = a.into_iter().enumerate().partition_map(|(i, foo)| {
        if i % 2 == 0 {
            Either::Left(foo)
        } else {
            Either::Right(foo)
        }
    });

    println!("{:?}, {:?}", b, c);
}

0
投票

要在Iterator上迭代时获取索引,您可以使用Iterator::enumerate

let arr = [1, 2, 3, 4];
let (a, b): (Vec<_>, Vec<_>) = arr.iter().enumerate().partition(|(i, _)| i % 2 == 0);

问题是“不加枚举”向量。为此,您可以使用此功能:

fn unenumerate<T>(a: impl IntoIterator<Item = (usize, T)>) -> Vec<T> {
    a.into_iter().map(|(_, e)| e).collect()
}

结合使用,可以获得理想的效果:

println!("{:?} {:?}", unenumerate(a), unenumerate(b)); // [1, 3] [2, 4]
© www.soinside.com 2019 - 2024. All rights reserved.