问题描述
假设- Vec< f32>
不没有任何 NaN
值或表现出任何 NaN
行为。
Assumption -- The Vec<f32>
does not have any NaN
values or exhibit any NaN
behavior.
采用以下示例集:
0.28
0.3102
0.9856
0.3679
0.3697
0.46
0.4311
0.9781
0.9891
0.5052
0.9173
0.932
0.8365
0.5822
0.9981
0.9977
获得指数的最新颖,最稳定的方法是什么上面列表中最高值的 strong>(值可以为负)?
What is the neatest and most stable way to get the index of the highest value in the above list (values can be negative)?
我的最初尝试如下:
let _tmp = *nets.iter().max_by(|i, j| i.partial_cmp(j).unwrap()).unwrap();
let _i = nets.iter().position(|&element| element == _tmp).unwrap();
其中 nets
是& Vec< f32>
。在我看来,这显然是不正确的。
Where nets
is a &Vec<f32>
. Which to me seems blatantly incorrect.
此功能的Python等效项(考虑到上述假设):
The Python equivalent of this that works (taking into consideration the above assumption):
_i = nets.index(max(nets))
推荐答案
我可能会做这样的事情:
I will probably do something like this:
fn main() -> Result<(), Box<std::error::Error>> {
let samples = vec![
0.28, 0.3102, 0.9856, 0.3679, 0.3697, 0.46, 0.4311, 0.9781, 0.9891, 0.5052, 0.9173, 0.932,
0.8365, 0.5822, 0.9981, 0.9977,
];
// Use enumerate to get the index
let mut iter = samples.iter().enumerate();
// we get the first entry
let init = iter.next().ok_or("Need at least one input")?;
// we process the rest
let result = iter.try_fold(init, |acc, x| {
// return None if x is NaN
let cmp = x.1.partial_cmp(acc.1)?;
// if x is greater the acc
let max = if let std::cmp::Ordering::Greater = cmp {
x
} else {
acc
};
Some(max)
});
println!("{:?}", result);
Ok(())
}
这可能是通过在Iterator上添加特征,例如使用功能 try_max_by
来实现。
This could be implemented by adding a trait on Iterator with for example the function try_max_by
.
这篇关于在Rust中的slice或Vec中获取最大或最小浮点值的索引的惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!