如何压缩两个以上的迭代器? [英] How can I zip more than two iterators?

查看:119
本文介绍了如何压缩两个以上的迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更直接,更易读的方法来完成以下任务:

Is there a more direct and readable way to accomplish the following:

fn main() {
    let a = [1, 2, 3];
    let b = [4, 5, 6];
    let c = [7, 8, 9];
    let iter = a.iter()
        .zip(b.iter())
        .zip(c.iter())
        .map(|((x, y), z)| (x, y, z));
}

也就是说,如何从n次迭代中构建一个迭代器,产生n-元组?

That is, how can I build an iterator from n iterables which yields n-tuples?

推荐答案

您可以使用 izip!()中的宏crate itertools ,它为任意多个迭代器实现这一点:

You can use the izip!() macro from the crate itertools, which implements this for arbitrary many iterators:

#[macro_use]
extern crate itertools;

fn main() {

    let a = [1, 2, 3];
    let b = [4, 5, 6];
    let c = [7, 8, 9];

    // izip!() accepts iterators and/or values with IntoIterator.
    for (x, y, z) in izip!(&a, &b, &c) {

    }
}

您必须在Cargo.toml中添加对itertools的依赖,使用最新的版本。示例:

You would have to add a dependency on itertools in Cargo.toml, use whatever version is the latest. Example:

[dependencies]
itertools = "0.7"

这篇关于如何压缩两个以上的迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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