我有一个散列哈希包含键,值和形式的计数((k1,v1),c1).我正在尝试编写一个子例程,该子例程返回作为具有最大计数的参数传递的键的值.例如,如果我有:
%hash = (
"a" => {
"b" => 2,
"c" => 1,
},
"d" => {
"e" => 4,
},
);
Run Code Online (Sandbox Code Playgroud)
打了个电话:
print &function("a");
Run Code Online (Sandbox Code Playgroud)
它应该打印"b",因为键"a"的最大计数为2,其中"b"为其值.这是我到目前为止的代码:
sub function() {
$key = $_[0];
if(exists($hash{$key})) {
while (my ($value, $count) = each %{$hash{$key}}) {
#logic goes here
}
} else {
return "$key does not exist";
}
}
Run Code Online (Sandbox Code Playgroud)
sub不需要知道有关外部哈希的任何信息,因此调用sub更为有意义,如下所示:
print key_with_highest_val($hash{a});
Run Code Online (Sandbox Code Playgroud)
sub只需要遍历该hash的所有元素,跟踪所看到的最高值以及看到它的键.
sub key_with_highest_val {
my ($h) = @_;
my $hi_v;
my $hi_k;
for my $k (keys(%$h)) {
my $v = $h->{$k};
if (!defined($hi_v) || $v > $hi_v) {
$hi_v = $v;
$hi_k = $k;
}
}
return $hi_k;
}
Run Code Online (Sandbox Code Playgroud)
正如Chris Charley指出的那样,List :: Util reduce可以简单地使用这个功能.使用上面推荐的调用约定,reduce解决方案如下:
use List::Util qw( reduce );
sub key_with_highest_val {
my ($h) = @_;
return reduce { $h->{$a} >= $h->{$b} ? $a : $b } keys(%$h);
}
Run Code Online (Sandbox Code Playgroud)
两个版本都会在那些与平局相关的关键字中返回任意关键字.
| 归档时间: |
|
| 查看次数: |
468 次 |
| 最近记录: |