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?
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With