返回具有最大值的所有散列键/值对

itz*_*tzy 3 perl hash

我有一个哈希(在Perl中),其中值都是数字.我需要创建另一个散列,其中包含第一个散列中的所有键/值对,其中值是所有值的最大值.

例如,给定

my %hash = (
    key1 => 2,
    key2 => 6,
    key3 => 6,
);
Run Code Online (Sandbox Code Playgroud)

我想创建一个包含以下内容的新哈希:

%hash_max = (
    key2 => 6,
    key3 => 6,
);
Run Code Online (Sandbox Code Playgroud)

我确信有很多方法可以做到这一点,但我正在寻找一个优雅的解决方案(并有机会学习!).

yst*_*sth 7

use List::Util 'max';
my $max = max(values %hash);
my %hash_max = map { $hash{$_}==$max ? ($_, $max) : () } keys %hash;
Run Code Online (Sandbox Code Playgroud)

或者是一次通过的方法(与另一个答案类似但略有不同):

my $max;
my %hash_max;
keys %hash; # reset iterator
while (my ($key, $value) = each %hash) {
    if ( !defined $max || $value > $max ) {
        %hash_max = ();
        $max = $value;
    }
    $hash_max{$key} = $value if $max == $value;
}
Run Code Online (Sandbox Code Playgroud)