本文介绍了slice :: chunks / windows是否有等效的迭代器循环对,三元组等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一次迭代多个变量,重叠是非常有用的()或不是()。
It can be useful to iterate over multiple variables at once, overlapping (slice::windows
), or not (slice::chunks
).
这仅适用于切片;是否可以为迭代器执行此操作,为方便起见使用元组?
This only works for slices; is it possible to do this for iterators, using tuples for convenience?
可能会写出如下内容:
for (prev, next) in some_iter.windows(2) {
...
}
如果没有,是否可以将其作为现有迭代器的特征实现?
If not, could it be implemented as a trait on existing iterators?
推荐答案
使用,最多4元组:
It's possible to take chunks of an iterator using Itertools::tuples
, up to a 4-tuple:
extern crate itertools;
use itertools::Itertools;
fn main() {
let some_iter = vec![1, 2, 3, 4, 5, 6].into_iter();
for (prev, next) in some_iter.tuples() {
println!("{}--{}", prev, next);
}
}
()
1--2
3--4
5--6
以及:
extern crate itertools;
use itertools::Itertools;
fn main() {
let some_iter = vec![1, 2, 3, 4, 5, 6].into_iter();
for (prev, next) in some_iter.tuple_windows() {
println!("{}--{}", prev, next);
}
}
()
1--2
2--3
3--4
4--5
5--6
这篇关于slice :: chunks / windows是否有等效的迭代器循环对,三元组等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!