在分区功能中获取项目的索引

时间:2019-03-25 09:01:48

标签: rust

我需要将数组/向量分割成锈,并在文档中找到partition。似乎传递给var poolData = { UserPoolId : <POOL_ID>, ClientId : <CLIENT_ID>, }; var userPool = new AWSCognito.CognitoUserPool(poolData); var attributeList = []; var dataEmail = { Name : 'email', Value : 'email@mydomain.com' }; var dataPhoneNumber = { Name : 'phone_number', Value : '+15555555555' }; var grandMaName = { Name : 'custom:grandMaName', Value : 'granny' }; var attributeEmail = new AWSCognito.CognitoUserAttribute(dataEmail); var attributePhoneNumber = new AWSCognito.CognitoUserAttribute(dataPhoneNumber); var attributeGrandMaName = new AWSCognito.CognitoUserAttribute(grandMaName); attributeList.push(attributeEmail); attributeList.push(attributePhoneNumber); attributeList.push(grandMaName); userPool.signUp(userData.Username, userData.Password, attributeList, null, function(err, result){ if (err) { console.log(err); return; } cognitoUser = result.user; console.log('user name is ' + cognitoUser.getUsername()); console.log('Now go to Cognito console and confirm the user.') }); 的回调函数只能访问数组的项目。如何获得商品的索引?

例如,给一个数组 protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Before "drawPath" canvas.drawColor(this.baseColor); if (this.bitmap != null) { canvas.drawBitmap(this.bitmap, getHeight(), getWidth(), emptyPaint); } for (int i = 0; i < this.historyPointer; i++) { Path path = this.pathLists.get(i); Paint paint = this.paintLists.get(i); canvas.drawTextOnPath(text, path, 0, 10, paint); } this.canvas = canvas; } ,我如何根据它们的位置将其分成两个,所以第一个将是partition,因为它们每个都有一个偶数位置(1和3索引0和2(是偶数),第二个是[1, 2, 3, 4]

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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]