我有perl代码,其中排序选择最小值,但如果一个值为0,则应忽略它。 这是没有过滤的排序功能:
sub desc_Emin
{
my($emin)=(sort{$b<=>$a} @_)[-1];
return $emin;
}
调用此函数并获取值:
$desc_mv[$n]=desc_Emin($descs_a[$n],$descs_b[$n],$descs_c[$n]);
例如,有列表:
descs_a descs_b descs_c
1 4 5
0 1 3
0 0 0
2 2 0
排序后[$ desc_mv]应为:
1
1
0
2
如何过滤而不添加大量'if'语句?最好在“$ desc_mv [$ n] = desc_Emin(...”部分?
中过滤零。我的快速时态解决方案如下:
if($descs_a[$n] == $descs_b[$n] and $descs_b[$n] == $descs_c[$n] ){
$desc_mv[$n]=$descs_a[$n];
}
else{
use Switch;
switch($descs_a[$n]){
case 0 {$descs_a[$n] = 99999999999999};
}
use Switch;
switch($descs_b[$n]){
case 0 {$descs_b[$n] = 99999999999999};
}
use Switch;
switch($descs_c[$n]){
case 0 {$descs_c[$n] = 99999999999999};
}
$desc_mv[$n]=desc_Emin($descs_a[$n],$descs_b[$n],$descs_c[$n]);
}
答案 0 :(得分:2)
你过度复杂的事情。您需要扫描所有值,跳过0并记住每个新值(如果它小于先前记住的值)。只需在Perl中写出来:
sub desc_Emin {
my $min = 0;
for my $val (@_) {
# if we're remembering 0, replace it with anything OR (if new value is not 0 and smaller than what we remember, remember that)
if ($min == 0 || ($val != 0 && $min > $val)) { $min = $val }
}
return $min;
}