在 Rust 中逐个元素比较 2 个向量或字符串的最佳方法是什么,同时能够对每对元素进行处理?例如,如果您想计算不同元素的数量。这是我正在使用的:
let mut diff_count: i32 = 0i32;
for (x, y) in a.chars().zip(b.chars()) {
if x != y {
diff_count += 1i32;
}
}
这是正确的方法还是有更规范的方法?
最佳答案
要获取匹配元素的数量,我可能会使用 filter
和 count
。
fn main() {
let a = "Hello";
let b = "World";
let matching = a.chars().zip(b.chars()).filter(|&(a, b)| a == b).count();
println!("{}", matching);
let a = [1, 2, 3, 4, 5];
let b = [1, 1, 3, 3, 5];
let matching = a.iter().zip(&b).filter(|&(a, b)| a == b).count();
println!("{}", matching);
}
-
Iterator::zip
采用两个迭代器并生成每个迭代器值的元组的另一个迭代器。 -
Iterator::filter
获取对迭代器值的引用并丢弃谓词闭包返回false
的任何值。这将执行比较。 -
Iterator::count
计算迭代器中元素的数量。
请注意,Iterator::zip
在一个 迭代器耗尽时停止迭代。如果您需要不同的行为,您可能也对
Itertools::zip_longest
或 Itertools::zip_eq
.
关于rust - 逐个元素比较 2 个向量或字符串的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29504514/