Step By Samples Every Nth Element
Sample every Nth element with step_by, which always keeps the first item and walks the rest at a fixed stride, so uniform sampling never needs grouping.
Code
fn main() {
let readings: Vec<u32> = (1..=100).collect();
// step_by:每隔 N 个取一个,首元素总在结果里
let sampled: Vec<u32> = readings.iter().step_by(10).copied().collect();
println!("{sampled:?}");
// 对 range 直接抽步:1 起、步长 3
let every_third: String = (1..=10)
.step_by(3)
.map(|n| n.to_string())
.collect::<Vec<_>>()
.join(",");
println!("{every_third}");
// 对照 chunks:那是连续分块,step_by 是跨步抽取
let chunked: Vec<Vec<u32>> = readings.chunks(10).map(|c| c.to_vec()).take(2).collect();
println!("{chunked:?}");
}How the snippet works
Count the function main as the entire surface area of Step By Samples Every Nth Element.
Key statements
let chunked: Vec<Vec<u32>> = readings.chunks(10).map(|c| c.to_vec()).take(2).collect();
let sampled: Vec<u32> = readings.iter().step_by(10).copied().collect();
let readings: Vec<u32> = (1..=100).collect();
Interactive Tools for This Topic
FAQ
- How do you run Step By Samples Every Nth Element?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.