按值对多维散列进行排序并显示最高的 [英] Sort multidimensional hash by values and print the highest
问题描述
我有一个存储的多维哈希(%info
),具有以下结构:
I have a stored multidimensional hash (%info
) with following structure:
$info{$os}{$id}=$length;
foreach $os (keys %info){
foreach $id (keys %{$info{$os}}){
print "$os $id => " . $info{$os}{$id} ."\n" if (keys %info > 100);
}
}
这样,我可以读取哈希并仅打印出现次数超过100的那些$os
,但是现在我只想打印具有最大$ length(即值)的$id
.因此,我想按值对散列进行排序,并仅打印具有最高值的$os
和$id
.
With this, I can read the hash and print only those $os
with more than 100 occurrences, but now I would like to print only the $id
with highest $length (i.e., values). So I would like to sort the hash by values and print only $os
and $id
with highest value.
有帮助吗?
推荐答案
可以使用列表:: Util :: reduce 在每个顶级密钥中获取具有最大值的密钥
Can use List::Util::reduce to get the key with the largest value, within each top-level key
use List::Util qw(reduce);
for my $os (keys %info) {
my $id_max_length = reduce {
$info{$os}{$a} > $info{$os}{$b} ? $a : $b
} keys %{$info{$os}};
say "$os --> $id_max_length --> $info{$os}{$id_max_length}";
}
要在所有键中获得最高价值
To get the highest value among all keys
my ($max_os, $max_id) =
map { $_->[0], $_->[1] }
reduce { $info{$a->[0]}{$a->[1]} > $info{$b->[0]}{$b->[1]} ? $a : $b }
map { [$_, max_id_for_os($_)] }
keys %info;
say "$max_os -> $max_id -> $info{$max_os}{$max_id}";
sub max_id_for_os {
my ($os) = @_;
reduce { $info{$os}{$a} > $info{$os}{$b} ? $a : $b } keys %{$info{$os}}
}
或者,也许更简单,在循环中对顶级键进行比较
Or, perhaps simpler, compare in the loop over top-level keys
my ($max_os, $max_id) = do { # initialize
my ($os) = keys %info;
$os, (keys %{$info{$os}})[0];
};
for my $os (keys %info) {
my $mid =
reduce { $info{$os}{$a} > $info{$os}{$b} ? $a : $b }
keys %{$info{$os}};
($max_os, $max_id) = ($os, $mid)
if $info{$os}{$mid} > $info{$max_os}{$max_id};
}
say "Largest: $max_os -> $max_id -> $info{$max_os}{$max_id}";
这篇关于按值对多维散列进行排序并显示最高的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!