Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I zip more than two iterators?

Tags:

iterator

rust

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)); } 

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

like image 935
anderspitman Avatar asked Apr 16 '15 08:04

anderspitman


People also ask

Is zip iterable?

Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.

How do you zip in Rust?

If you want to zip two or three iterator value together then you can use zip() function for that. If we use zip() function in rust, it will always return us new iterator containing a tuple which will hole the value from both the iterator in sequence and keep on iterating until the last element is reached.


1 Answers

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

use itertools::izip;  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) {      } } 

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

[dependencies] itertools = "0.8" 
like image 88
bluss Avatar answered Sep 23 '22 07:09

bluss