rust iterator

通过迭代器提供的filter()collect()方法。

let list2: Vec<_> = (1..=100).filter(|i| i%3 == 0).collect();
assert_eq!(list1, list2);

 

 

take(k)取前面k个元素。

迭代器调用take()后,迭代器的所有权会被转移到take方法内部,因此一个迭代器的take方法只能调用一次。

assert_eq!(vec![1,2,3], (1..10).take(3).collect::<Vec<_>>());


nth(k)
取得迭代器剩余元素中第k个位置的元素,位置从0开始;之后,迭代器跳转到下一个位置。

let mut it = [1, 2, 3].iter();
assert_eq!(Some(&1), it.nth(0));
assert_eq!(Some(&2), it.nth(0));
assert_eq!(Some(&3), it.nth(0));
assert_eq!(None, it.nth(0));
assert_eq!(Some(3), (0..4).nth(3));

last()

只取最后一个元素,只能调用一次。

assert_eq!((1..4).last(), Some(3));



rev()反转
//反向遍历
println!("{:?}", "-".repeat(10));
//输出:4,3,2,1,0,
vec![0, 1, 2, 3, 4].iter().rev().for_each(|x|print!("{x},"));
println!();
//输出:9,8,7,6,5,4,3,2,1,0,
for i in (0..10).rev() {
print!("{:?},", i);
}
println!("\n{:?}", "-".repeat(10));

 

skip(k)跳过k个元素

assert_eq!(vec![2,3], (0..4).skip(2).collect::<Vec<_>>());

step_by(k),从第一个元素开始,每k个取一个出来
assert_eq!(vec![0,2,4,6], (0..7).step_by(2).collect::<Vec<_>>());

chain()方法对迭代器进行顺序拼接合并
let it = (0..5).chain(15..20);
//[0, 1, 2, 3, 4, 15, 16, 17, 18, 19]
println!("{:?}", it.collect::<Vec<_>>());

zip()将2个迭代器合并为一对一元组迭代器
let it = [1,3,5].iter().zip([2,4,6].iter());
assert_eq!(vec![(&1,&2),(&3,&4),(&5,&6)], it.collect::<Vec<(_,_)>>());
assert_eq!(vec![(0,'f'),(1,'o'),(2,'o')], (0..).zip("foo".chars()).collect::<Vec<_>>());

map()方法,对迭代器中每一个元素进行映射,返回一个新的迭代器
assert_eq!(vec![0,1,4,9,16], (0..5).map(|x|x*x).collect::<Vec<_>>());

 

 

对迭代器进行求值结算

//最大值
assert_eq!([1,2,3].iter().max(), Some(&3));
//最小值
assert_eq!([1,2,3].iter().min(), Some(&1));
// count()计算迭代器中元素的个数
assert_eq!([1,2,3].iter().count(), 3);
// 求和
assert_eq!([1,2,3].iter().sum::<i32>(), 6);

 

 

fold()方法,通过传入一个初始值和一个闭包累加器,对迭代器中的每一个元素依次进行处理并累加,最后返回累加结果。

assert_eq!(3, (1..3).fold(0, |acc, x|acc+x));
assert_eq!(6, (1..3).fold(0, |acc, x|acc+2*x));

posted @   CrossPython  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示