如何从 Perl 中的散列中获取最小值键
How to get minimum values key from hash in Perl
我有脚本可以从哈希值中选择最小值。
use strict;
use warnings;
use Data::Dumper;
use List::Util qw(min);
my @array = qw/50 51 52 53 54/;
my $time = 1596561300;
my %hash;
foreach my $element(@array){
$hash{$time} = $element;
$time += 6; #based on some condition incrementing the time to 6s
}
print Dumper(\%hash);
my $min = min values %hash;
print "min:$min\n";
在这里我可以得到 50
作为散列值中所有值的最小值。但是我怎样才能得到对应于最小值的哈希键,即1596561300
.
从键中,可以得到值。所以你想要具有最小关联值的键。
min LIST
可以写成reduce { $a <= $b ? $a : $b } LIST
,所以我们可以用
use List::Util qw( reduce );
my $key = reduce { $hash{$a} <= $hash{$b} ? $a : $b } keys %hash;
my $val = $hash{$key};
或
my ($key) = keys(%hash);
my $val = $hash{$key};
for (keys(%hash)) {
if ($hash{$_} < $val) {
$key = $_;
$val = $hash{$val};
}
}
请参阅@ikegami 的回答,以获得针对 OP 的确切问题的最干净、最快的解决方案。
如果您需要按值 numerically 排序的顺序访问其他键(我从您的示例假设这就是您想要的),请使用:
my @keys_sorted_by_value = sort { $hash{$a} <=> $hash{$b} } keys %hash;
# key with min value: $keys_sorted_by_value[0]
# ...
# key with max value: $keys_sorted_by_value[-1]
或按值排序ASCIIbetically:
my @keys_sorted_by_value = sort { $hash{$a} cmp $hash{$b} } keys %hash;
我有脚本可以从哈希值中选择最小值。
use strict;
use warnings;
use Data::Dumper;
use List::Util qw(min);
my @array = qw/50 51 52 53 54/;
my $time = 1596561300;
my %hash;
foreach my $element(@array){
$hash{$time} = $element;
$time += 6; #based on some condition incrementing the time to 6s
}
print Dumper(\%hash);
my $min = min values %hash;
print "min:$min\n";
在这里我可以得到 50
作为散列值中所有值的最小值。但是我怎样才能得到对应于最小值的哈希键,即1596561300
.
从键中,可以得到值。所以你想要具有最小关联值的键。
min LIST
可以写成reduce { $a <= $b ? $a : $b } LIST
,所以我们可以用
use List::Util qw( reduce );
my $key = reduce { $hash{$a} <= $hash{$b} ? $a : $b } keys %hash;
my $val = $hash{$key};
或
my ($key) = keys(%hash);
my $val = $hash{$key};
for (keys(%hash)) {
if ($hash{$_} < $val) {
$key = $_;
$val = $hash{$val};
}
}
请参阅@ikegami 的回答,以获得针对 OP 的确切问题的最干净、最快的解决方案。
如果您需要按值 numerically 排序的顺序访问其他键(我从您的示例假设这就是您想要的),请使用:
my @keys_sorted_by_value = sort { $hash{$a} <=> $hash{$b} } keys %hash;
# key with min value: $keys_sorted_by_value[0]
# ...
# key with max value: $keys_sorted_by_value[-1]
或按值排序ASCIIbetically:
my @keys_sorted_by_value = sort { $hash{$a} cmp $hash{$b} } keys %hash;