如何压缩两个以上的迭代器?
How can I zip more than two iterators?
是否有更直接和可读的方式来完成以下操作:
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 个元组的迭代器?
您可以使用 crate itertools 中的 izip!()
宏,它为任意多个迭代器实现了这一点:
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) {
}
}
您必须在 Cargo.toml 中添加对 itertools 的依赖,使用最新版本。示例:
[dependencies]
itertools = "0.8"
您还可以使用提供的 .zip
创建一个宏,
$ cat z.rs
macro_rules! zip {
($x: expr) => ($x);
($x: expr, $($y: expr), +) => (
$x.iter().zip(
zip!($($y), +))
)
}
fn main() {
let x = vec![1,2,3];
let y = vec![4,5,6];
let z = vec![7,8,9];
let zipped = zip!(x, y, z);
println!("{:?}", zipped);
for (a, (b, c)) in zipped {
println!("{} {} {}", a, b, c);
}
}
输出:
$ rustc z.rs && ./z
Zip { a: Iter([1, 2, 3]), b: Zip { a: Iter([4, 5, 6, 67]), b: IntoIter([7, 8, 9]), index: 0, len: 0 }, index: 0, len: 0 }
1 4 7
2 5 8
3 6 9
我希望能够对任意长的向量执行此操作,所以我必须手动实现:
fn transpose_records<T: Clone>(records: &Vec<Vec<T>>) -> Vec<Vec<T>> {
let mut transposed: Vec<Vec<T>> = vec![Vec::new(); records[0].len()];
for record in records {
for (index, element) in record.iter().enumerate() {
transposed[index].push(element.clone());
}
}
transposed
}
是否有更直接和可读的方式来完成以下操作:
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 个元组的迭代器?
您可以使用 crate itertools 中的 izip!()
宏,它为任意多个迭代器实现了这一点:
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) {
}
}
您必须在 Cargo.toml 中添加对 itertools 的依赖,使用最新版本。示例:
[dependencies]
itertools = "0.8"
您还可以使用提供的 .zip
创建一个宏,
$ cat z.rs
macro_rules! zip {
($x: expr) => ($x);
($x: expr, $($y: expr), +) => (
$x.iter().zip(
zip!($($y), +))
)
}
fn main() {
let x = vec![1,2,3];
let y = vec![4,5,6];
let z = vec![7,8,9];
let zipped = zip!(x, y, z);
println!("{:?}", zipped);
for (a, (b, c)) in zipped {
println!("{} {} {}", a, b, c);
}
}
输出:
$ rustc z.rs && ./z
Zip { a: Iter([1, 2, 3]), b: Zip { a: Iter([4, 5, 6, 67]), b: IntoIter([7, 8, 9]), index: 0, len: 0 }, index: 0, len: 0 }
1 4 7
2 5 8
3 6 9
我希望能够对任意长的向量执行此操作,所以我必须手动实现:
fn transpose_records<T: Clone>(records: &Vec<Vec<T>>) -> Vec<Vec<T>> {
let mut transposed: Vec<Vec<T>> = vec![Vec::new(); records[0].len()];
for record in records {
for (index, element) in record.iter().enumerate() {
transposed[index].push(element.clone());
}
}
transposed
}